将python文件编译成exe文件
第一种方法:我们只会生成一个exe文件,因为所有的库文件他都会包含在这个exe文件中
1、安装:pyinstaller
pip install pyinstaller
2、使用如下命令编译
pyinstaller -F -w GraphCut.py
3、会在项目下生成文件:NewCutUI.spec。之后我们需要在文件里添加导入的包。
原始生成文件:
# -*- mode: python ; coding: utf-8 -*- block_cipher = None a = Analysis(['NewCutUI.py'], pathex=['E:\\项目\\GraphCut\\graph_cut'], binaries=[], datas=[], hiddenimports=[], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, [], name='NewCutUI', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, upx_exclude=[], runtime_tmpdir=None, console=False )
修改后的文件:
# -*- mode: python ; coding: utf-8 -*- from PyInstaller.utils.hooks import collect_submodules block_cipher = None hiddenimports_numpy = collect_submodules('numpy') hidden_imports_PyQt4 = collect_submodules('PyQt4') hiddenimports_graph_cut = collect_submodules('graph_cut') hidden_imports_maxflow = collect_submodules('maxflow') hidden_imports_argparse = collect_submodules('argparse') hidden_imports_GraphMaker = collect_submodules('GraphMaker') hidden_imports_cv2 = collect_submodules('cv2') block_cipher = None all_hidden_imports = hiddenimports_numpy + hidden_imports_PyQt4+hiddenimports_graph_cut + hidden_imports_maxflow + hidden_imports_argparse + hidden_imports_GraphMaker + hidden_imports_cv2 a = Analysis(['NewCutUI.py'], pathex=['E:\\项目\\GraphCut\\graph_cut'], binaries=[], datas=[], hiddenimports=all_hidden_imports, hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, [], name='NewCutUI', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, upx_exclude=[], runtime_tmpdir=None, console=False )
4、使用:pyinstaller.exe NewCutUI.spec 进行打包,其中你需要找到pyinstaller.exe文件位置,我的位置:D:\anaconda\Anaconda\envs\pytorch\Scripts\pyinstaller.exe
pyinstaller.exe E:\项目\GraphCut\graph_cut\NewCutUI.spec
最后生成的exe文件目录:D:\anaconda\Anaconda\envs\pytorch\Scripts\dist\NewCutUI.exe
我在外面导包的时候经常遇到错误,所以直接在文件里面填了导包的内容。最后exe文件可能会很大,大概都是使用import这个方法导包,虽然我使用from * import *没小多少。
第二种方法:他会把一些库的依赖生成dll动态链接库文件,所以dist下会有很多个文件。
如果上述方法出现 "failed to execute script”这个错误,我们可以使用下面这个方法,同样可以得到exe文件:
只需要执行这行代码就ok了:pyinstaller.exe computer_S.py
你可以在当前目录下找到:../dist/computer_S/computer_S.exe文件