天天看點

pyinstaller使用-python項目轉換成exe可執行檔案安裝pyinstallerpyinstaller的使用附錄pyinstaller生成的exe檔案執行過程

http://blog.csdn.net/pipisorry/article/details/50620122

Python不是每個人的計算機裡面都有安裝,當您寫了一個好用的工具,需要一個standalone exectuable環境的需求。并且用python寫些腳本什麼的,有時候腳本寫完以後,每次運作都得在IDE打開在運作,很麻煩,是以經常将python編譯成exe。

本文介紹如何将一個python項目(或者簡單一點一個python腳本檔案)轉化為windows下的可執行檔案。

轉化要使用python轉換為exe可執行檔案的庫,一個是py2exe,另外一個就是PyInstaller。

py2exe:

打包好的exe隻能在相同的系統下運作,比如你在XP系統用py2exe打包好的exe隻能在XP上運作,在win7上肯定有問題,而且也是存在在别的XP機子上也可能不能運作,因為一些别的機子可能會缺少dll檔案;

打包的檔案也需要打包同exe下的dll,和一些庫的壓縮包,不然exe根本跑不起來

還需要另外的其他庫檔案配置。

PyInstaller:

可以隻是生成單獨的可執行程式

且支援的版本也多:2.3到2.7都支援。以及x64也支援

也可以自定義圖示

本文介紹pyinstaller的使用。

安裝pyinstaller

pyinstaller支援python2和python3

指令行安裝:pip install pyinstaller

或者去下載下傳安裝:PyInstaller 3.1 (tar.gz) | http://sourceforge.net/projects/pywin32/files/pywin32/Build%20217/

Note: windows下轉換要先安裝pywin32:  pip install pywin32[pywin32的安裝]

皮皮blog

pyinstaller的使用

指令行中轉換py檔案為exe檔案

[email protected] /e/mine/python_workspace/nlp(dev)

$pyinstaller -F E:/mine/python_workspace/NLP/TargetOpinion/TargetOpinionMain.py

在指令行目前路徑/e/mine/python_workspace/nlp中會生成

dist目錄(目錄裡面有可執行檔案)

build目錄(生成exe的中間檔案)

spec檔案(要轉換檔案的同一目錄下,用于生成exe檔案,可以修改來自定義生成exe的屬性)

pyinstaller使用-python項目轉換成exe可執行檔案安裝pyinstallerpyinstaller的使用附錄pyinstaller生成的exe檔案執行過程

指定dist生成目錄路徑(而不是指令行目前目錄)

pyinstaller -F E:/mine/python_workspace/test0/testMain.py --distpath=E:/mine/python_workspace/test0/dist

壓縮生成的exe檔案

用UPX去壓縮,壓縮後所生成的exe檔案的大小,會小得多

--upx        I mentioned that this is a great option, and it is, but it's really slow, especially as your source file gets bigger.  It's a great option for your final compile before distributing, but you might save a lot of time if you turn it off until then.

先下載下傳http://upx.sourceforge.net/解壓到要轉換到的py檔案目錄下

pyinstaller參數中添加upx路徑

pyinstaller -F E:/mine/python_workspace/NLP/TargetOpinion/TargetOpinionMain.py--upx-dir upx391w

[http://pythonhosted.org/PyInstaller/#using-upx]

直接進入界面程式

pyinstaller生成的exe檔案是從指令行開始執行的,如果之前的程式是界面程式(如pyqt界面開始執行的),則要改成從界面執行,這樣就不會看到指令行輸出了(如bug錯誤輸出、print輸出等)

pyinstaller -Fw E:/mine/python_workspace/NLP/TargetOpinion/TargetOpinionMain.py

當然,如果是在調試期間,建議不要加w參數,這樣就可以從指令行看到bug提示了。

修改中間檔案spec檔案生成自定義exe檔案

修改中間檔案,再去生成exe檔案

如,在生成exe檔案的同時,在exe目錄下(dist目錄)生成一個資料檔案,相當于将python項目中的資料檔案拷貝到dist目錄

修改spec檔案中datas如下:datas= [ ('nlptest/patternFile.txt', '.' ) ],

pyinstaller -F E:/mine/python_workspace/test0/testMain.spec

[http://pythonhosted.org/PyInstaller/#using-spec-files]

一步一步生成

當然也可以一步一步生成,并使用中間檔案

生成中間檔案:python Makespec.py --console --onefile NotePad\notepad.py

再build生成exe檔案:python Build.py NotePad\notepad.spec

[關于python打包成exe的一點經驗之談]

[.py程式轉換成.exe可執行程式]

py代碼調用pyinstaller,将.py檔案轉換成exe檔案(推薦)

當然也可以在TargetOpinionMain.py同目錄下建立一個轉換檔案TargetPy2exe.py:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = '将TargetOpinionMain python項目轉換為exe檔案'
__author__ = '皮'
__email__ = '[email protected]'
"""
from PyInstaller.__main__ import run

if __name__ == '__main__':
    opts = ['TargetOpinionMain.py', '-F']
    # opts = ['TargetOpinionMain.py', '-F', '-w']
    # opts = ['TargetOpinionMain.py', '-F', '-w', '--icon=TargetOpinionMain.ico','--upx-dir','upx391w']
    run(opts)
      

效果同指令行執行是一樣的,隻不過使用IDE執行這個轉換代碼,出錯的話會有出錯棧提示,可以很快到達出錯位置;并且生成的build、dist目錄就在本目錄下,不用擔心在指令行中執行目錄錯亂,找不到或者搞混dist目錄。

pyinstaller生成exe檔案後,資料檔案讀取路徑的改變

python項目中讀取檔案會出錯,其原因是讀取的檔案路徑不是原來的了,因為所有檔案都編譯了,成了一個檔案exe檔案。

檔案目錄的改變可參考:[pyinstaller 生成單一的EXE檔案之後擷取目前目錄的方法]

如果pythony代碼中有讀取檔案操作,解決方案見:[pyinstaller相關錯誤]

皮皮blog

附錄

pyinstaller參數

General Options

-h, --help show this help message and exit
-v, --version Show program version info and exit.
--distpath DIR Where to put the bundled app (default: ./dist)
--workpath WORKPATH
Where to put all the temporary work files, .log, .pyz and etc. (default: ./build)
-y, --noconfirm
Replace output directory (default: SPECPATH/dist/SPECNAME) without asking for confirmation
--upx-dir UPX_DIR
Path to UPX utility (default: search the execution path)
-a, --ascii Do not include unicode encoding support (default: included if available)
--clean Clean PyInstaller cache and remove temporary files before building.
--log-level LEVEL
Amount of detail in build-time console messages. LEVEL may be one of DEBUG, INFO, WARN, ERROR, CRITICAL (default: INFO).

What to generate

-D, --onedir Create a one-folder bundle containing an executable (default)
-F, --onefile Create a one-file bundled executable.
--specpath DIR Folder to store the generated spec file (default: current directory)
-n NAME, --name NAME
Name to assign to the bundled app and spec file (default: first script's basename)

What to bundle, where to search

-p DIR, --paths DIR
A path to search for imports (like using PYTHONPATH). Multiple paths are allowed, separated by ':', or use this option multiple times
--hidden-import MODULENAME, --hiddenimport MODULENAME
Name an import not visible in the code of the script(s). This option can be used multiple times.
--additional-hooks-dir HOOKSPATH
An additional path to search for hooks. This option can be used multiple times.
--runtime-hook RUNTIME_HOOKS
Path to a custom runtime hook file. A runtime hook is code that is bundled with the executable and is executed before any other code or module to set up special features of the runtime environment. This option can be used multiple times.
--exclude-module EXCLUDES
Optional module or package (his Python names, not path names) that will be ignored (as though it was not found). This option can be used multiple times.
--key KEY The key used to encrypt Python bytecode.

How to generate

-d, --debug Tell the bootloader to issue progress messages while initializing and starting the bundled app. Used to diagnose problems with missing imports.
-s, --strip Apply a symbol-table strip to the executable and shared libs (not recommended for Windows)
--noupx Do not use UPX even if it is available (works differently between Windows and *nix)

Windows and Mac OS X specific options

-c, --console, --nowindowed
Open a console window for standard i/o (default)
-w, --windowed, --noconsole
Windows and Mac OS X: do not provide a console window for standard i/o. On Mac OS X this also triggers building an OS X .app bundle. This option is ignored in *NIX systems.
-i <FILE.ico or FILE.exe,ID or FILE.icns>, --icon <FILE.ico or FILE.exe,ID or FILE.icns>
FILE.ico: apply that icon to a Windows executable. FILE.exe,ID, extract the icon with ID from an exe. FILE.icns: apply the icon to the .app bundle on Mac OS X

Windows specific options

--version-file FILE
add a version resource from FILE to the exe
-m <FILE or XML>, --manifest <FILE or XML>
add manifest FILE or XML to the exe
-r RESOURCE, --resource RESOURCE
Add or update a resource to a Windows executable. The RESOURCE is one to four items, FILE[,TYPE[,NAME[,LANGUAGE]]]. FILE can be a data file or an exe/dll. For data files, at least TYPE and NAME must be specified. LANGUAGE defaults to 0 or may be specified as wildcard * to update all resources of the given TYPE and NAME. For exe/dll files, all resources from FILE will be added/updated to the final executable if TYPE, NAME and LANGUAGE are omitted or specified as wildcard *.This option can be used multiple times.
--uac-admin Using this option creates a Manifest which will request elevation upon application restart.
--uac-uiaccess Using this option allows an elevated application to work with Remote Desktop.

Windows Side-by-side Assembly searching options (advanced)

--win-private-assemblies
Any Shared Assemblies bundled into the application will be changed into Private Assemblies. This means the exact versions of these assemblies will always be used, and any newer versions installed on user machines at the system level will be ignored.
--win-no-prefer-redirects
While searching for Shared or Private Assemblies to bundle into the application, PyInstaller will prefer not to follow policies that redirect to newer versions, and will try to bundle the exact versions of the assembly.

Mac OS X specific options

--osx-bundle-identifier BUNDLE_IDENTIFIER
Mac OS X .app bundle identifier is used as the default unique program name for code signing purposes. The usual form is a hierarchical name in reverse DNS notation. For example: com.mycompany.department.appname (default: first script's basename)

Shortening the Command

Because of its numerous options, a full pyinstaller command can become very long. You will run the same command again and again as you develop your script. You can put the command in a shell script or batch file, using line continuations to make it readable. For example, in Linux:

pyinstaller --noconfirm --log-level=WARN \
    --onefile --nowindow \
    --hidden-import=secret1 \
    --hidden-import=secret2 \
    --upx-dir=/usr/local/share/ \
    myscript.spec
      

Or in Windows, use the little-known BAT file line continuation:

pyinstaller --noconfirm --log-level=WARN ^
    --onefile --nowindow ^
    --hidden-import=secret1 ^
    --hidden-import=secret2 ^
    --icon-file=..\MLNMFLCN.ICO ^
    myscript.spec      

[http://pythonhosted.org/PyInstaller/#options]

pyinstaller-2.0 參數(翻譯)

pyinstaller使用-python項目轉換成exe可執行檔案安裝pyinstallerpyinstaller的使用附錄pyinstaller生成的exe檔案執行過程

Note:--onefile前面是兩個-。

-F    制作獨立的可執行程式

-D    制作出的檔案存放在同一個檔案夾下(預設值)

-K    包含TCL/TK(對于使用了TK的,最好加上這個選項,否則在未安裝TK的電腦上無法運作)

-w     制作視窗程式

-c    制作指令行程式(預設)

-X    制作使用UPX壓縮過的可執行程式(推薦使用這個選項,需要下載下傳UPX包,解壓後upx.exe放在Python(非PyInstaller)安裝目錄下,下載下傳upx308w.zip)

-o DIR  指定輸出SPEC檔案路徑(這也決定了最後輸出的exe檔案路徑)

--icon=[ICO檔案路徑] 指定程式圖示

-v [指定檔案] 指定程式版本資訊

-n [指定程式名] 指定程式名稱

pyinstaller生成的exe檔案執行過程

單獨生成一個exe檔案(-F參數)後,exe檔案是怎麼運作的:

How the One-File Program Works

The bootloader is the heart of the one-file bundle also. When started it creates a temporary folder in the appropriate temp-folder location for this OS. The folder is named _MEIxxxxxx, where xxxxxx is a random number.

The one executable file contains an embedded archive of all the Python modules used by your script, as well as compressed copies of any non-Python support files (e.g. .so files). The bootloader uncompresses the support files and writes copies into the the temporary folder. This can take a little time. That is why a one-file app is a little slower to start than a one-folder app.

After creating the temporary folder, the bootloader proceeds exactly as for the one-folder bundle, in the context of the temporary folder. When the bundled code terminates, the bootloader deletes the temporary folder.

[http://pythonhosted.org/PyInstaller/#how-the-one-file-program-works]

What happens during execution of bootloader:

  1. First process: bootloader starts.
    1. If one-file mode, extract bundled files to temppath_MEIxxxxxx
    2. Set/unset various environment variables, e.g. override LD_LIBRARY_PATH on Linux or LIBPATH on AIX; unset DYLD_LIBRARY_PATH on OSX.
    3. Set up to handle signals for both processes.
    4. Run the child process.
    5. Wait for the child process to finish.
    6. If one-file mode, delete temppath_MEIxxxxxx.注意,exe檔案運作完成後,temp目錄下的臨時檔案_mei***就會被删除。
  2. Second process: bootloader itself started as a child process.
    1. On Windows set the activation context.
    2. Load the Python dynamic library. The name of the dynamic library is embedded in the executable file.
    3. Initialize Python interpreter: set sys.path, sys.prefix, sys.executable.
    4. Run python code.

Running Python code requires several steps:

  1. Run the Python initialization code which prepares everything for running the user's main script. The initialization code can use only the Python built-in modules because the general import mechanism is not yet available. It sets up the Python import mechanism to load modules only from archives embedded in the executable. It also adds the attributes frozen and _MEIPASS to the sys built-in module.
  2. Execute any run-time hooks: first those specified by the user, then any standard ones.
  3. Install python "egg" files. When a module is part of a zip file (.egg), it has been bundled into the ./eggs directory. Installing means appending .egg file names to sys.path. Python automatically detects whether an item in sys.path is a zip file or a directory.
  4. Run the main script.

[http://pythonhosted.org/PyInstaller/#bootloader]

py2exe使用參考

[http://www.py2exe.org/index.cgi/Tutorial]

from:http://blog.csdn.net/pipisorry/article/details/50620122

ref:Simple guide to using PyInstaller

PyInstaller Manual*