用py2exe打包python檔案成執行擋(exe)

使用py2exe可以將.py檔打包成可執行檔(python 2.x)

  1. 安裝py2exe,最簡單的方法是透過pip安裝
    pip install py2exe
    
    或是直接從官網上面下載安裝
  2. 準備要被打包的.py檔,例如"hello.py"
  3. print "Hello World!"
  4. 撰寫setup.py檔
  5. from distutils.core import setup
    import py2exe
    setup(console=['hello.py'])
  6. 使用Distutils的install指令安裝第三方軟體
  7. python setup.py install
  8. 開始打包
    C:\Tutorial>python setup.py py2exe
    running py2exe
    *** searching for required modules ***
    *** parsing results ***
    creating python loader for extension 'zlib'
    creating python loader for extension 'unicodedata'
    creating python loader for extension 'bz2'
    *** finding dlls needed ***
    *** create binaries ***
    *** byte compile python files ***
    byte-compiling C:\Tutorial\build\bdist.win32\winexe\temp\bz2.py to bz2.pyc
    byte-compiling C:\Tutorial\build\bdist.win32\winexe\temp\unicodedata.py to unicodedata.pyc
    byte-compiling C:\Tutorial\build\bdist.win32\winexe\temp\zlib.py to zlib.pyc
    skipping byte-compilation of c:\Python24\lib\StringIO.py to StringIO.pyc
    
    [skipping many lines for brevity]
    
    skipping byte-compilation of c:\Python24\lib\warnings.py to warnings.pyc
    *** copy extensions ***
    *** copy dlls ***
    copying c:\Python24\lib\site-packages\py2exe\run.exe -> C:\Tutorial\dist\hello.exe
    
    *** binary dependencies ***
    Your executable(s) also depend on these dlls which are not included,
    you may or may not need to distribute them.
    
    Make sure you have the license if you distribute any of them, and
    make sure you don't distribute files belonging to the operating system.
    
       ADVAPI32.dll - C:\WINDOWS\system32\ADVAPI32.dll
       USER32.dll - C:\WINDOWS\system32\USER32.dll
       SHELL32.dll - C:\WINDOWS\system32\SHELL32.dll
       KERNEL32.dll - C:\WINDOWS\system32\KERNEL32.dll
    
    C:\Tutorial>
    
  9. 找到編譯好的hello.exe(在cwd的dist資料夾裡),試試看能不能用
  10. C:\Tutorial\dist>hello.exe
    Hello World

Setup.py的進階設定


from distutils.core import setup
import py2exe

includes = []
excludes = []
packages = []
dll_excludes = []

setup(
    data_files= [],
 options = {'py2exe': {
        'includes': includes,
        'excludes': excludes,
        'packages': packages,
        'dll_excludes': dll_excludes,
        "bundle_files": 3,
    }},

    version = "1.0.0",
    description = "2018,pica,
    name = "test exe",
    zipfile=None,
    windows=['hello.py'],
onsole=["hello.py", "hello1.py", "hello2.py"])
    )
data_files:執行exe檔時需要的外部資料,比如說.png之類的,類型是list
windows:若要用其他gui視窗不用console,就下這個指令,內容為list
console:打包成一個console的exes。windows跟console指令可以一起下
includes:包含哪些模組
excludes:不包含哪些模組
packages:包含subpackages
dll_excludes:不包含哪些dll
bundle_files:3=包含.dll檔,2=不包含
更多範例在官網教學裡
http://www.py2exe.org/index.cgi/ListOfOptions

留言