執行python.py文件,pyinstaller使用-python項目轉換成exe可執行文件

 2023-12-09 阅读 30 评论 0

摘要:http://blog.csdn.net/pipisorry/article/details/50620122 Python不是每個人的計算機里面都有安裝,當您寫了一個好用的工具,需要一個standalone exectuable環境的需求。并且用python寫些腳本什么的,有時候腳本寫完以后,每次運行都得在IDE打開在運

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文件

pi@PIPI /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的屬性)


指定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__ = 'pipisorry@126.com'
"""
from PyInstaller.__main__ import runif __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)

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 參數(翻譯)

QQ截圖20130403234716.png

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*


版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/4/194072.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息