將Python指令檔封裝成可執行檔,
將Python指令檔封裝成可執行檔,其目的有二:
一則: 不需要依賴Python編譯器就可以運行軟體
二則: 不想讓自己的源碼公布出去
常用的工具有: py2exe、cx_freeze等
【工具:py2exe】
安裝該工具很簡單:
只需要從官方網站:http://www.py2exe.org/下載與版本對應的安裝程式,點擊下一步即可完成安裝。
安裝後,執行import py2exe,不報錯則表示安裝成功!
>>> import py2exe>>>
NOTE: 目前該工具只支援到Python2.7, 對於Python3而言,必須藉助另外一個工具:cx_freeze
第一步: 準備原始碼,假如名為:Hello.py
第二步: 準備編譯指令碼,假如名為:setup.py
from distutils.core import setupimport py2exesetup(windows=['Hello.py'])
第三步: 運行命令: setup.py py2exe
D:\temp>setup.py py2exe
運行之後,會在我當前啟動並執行目錄下(D:\temp)預設產生
dict目錄,裡面的檔案如下:
預設情況下,py2exe在目錄dist下建立以下這些必須的檔案:1、一個或多個exe檔案。如本例為: Hello.exe2、python##.dll。 如本例中: Python27.dll3、.pyd檔案,它們是已編譯的副檔名,它們是exe檔案所需要的;加上其它的.dll檔案,這些.dll是.pyd所需要的。4、一個library.zip檔案,它包含了已編譯的純的python模組如.pyc或.pyo
第四步: 雙擊Hello.exe可執行檔,跟原始碼運行後同樣的結果:
1: 執行setup.py --help擷取協助資訊
Global options: --verbose (-v) run verbosely (default) --quiet (-q) run quietly (turns verbosity off) --dry-run (-n) don't actually do anything --help (-h) show detailed help message --no-user-cfg ignore pydistutils.cfg in your home directoryOptions for 'py2exe' command: --optimize (-O) optimization level: -O1 for "python -O", -O2 for "python -OO", and -O0 to disable [default: -O0] --dist-dir (-d) directory to put final built distributions in (default is dist) --excludes (-e) comma-separated list of modules to exclude --dll-excludes comma-separated list of DLLs to exclude --ignores comma-separated list of modules to ignore if they are not found --includes (-i) comma-separated list of modules to include --packages (-p) comma-separated list of packages to include --compressed (-c) create a compressed zipfile --xref (-x) create and show a module cross reference --bundle-files (-b) bundle dlls in the zipfile or the exe. Valid levels are 1, 2, or 3 (default) --skip-archive do not place Python bytecode files in an archive, put them directly in the file system --ascii (-a) do not automatically include encodings and codecs --custom-boot-script Python file that will be run when setting up the runtime environmentusage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup.py --help [cmd1 cmd2 ...] or: setup.py --help-commands or: setup.py cmd --help
2: 一個詳細的編譯指令碼
# -*- coding: cp936 -*-from distutils.core import setupimport py2exeincludes = ["encodings", "encodings.*"]options = {"py2exe": {"compressed": 1, # 壓縮 "optimize": 2, # 最佳化層級 "ascii": 1, # "includes":includes, # 編碼方式 "bundle_files": 1 # 所有檔案打包成一個zipfile或exe檔案,有效層級1,2,3 }}setup( options=options, # 是否需要可選項,預設為None zipfile=None, # 是否需要壓縮像,預設為None console=[{"script": "HelloCmd.py", "icon_resources": [(1, "pc.ico")]}], # 針對CMD控制連接埠 windows=[{"script": "HelloWin.py", "icon_resources": [(1, "pc.ico")]}], # 針對GUI圖形視窗 data_files=[("magic",["App_x86.exe",]),], version = "v1.01", # 版本資訊 description = "py2exe testing",# 描述資訊 name = "Hello, Py2exe", # 名字資訊)詳情,請參考官方文檔:
http://www.py2exe.org/