1,首先安装pyinstaller
pip3 install pyinstaller # 安装pyinstaller
2,打包文件成exe
pyinstaller -F run.py # run 是需要打包的文件名
3,打包完成,在dist文件夹将run.exe放到上一级文件
4,运行文件出现bug,WARNING: file already exists but should not: C:\Users\abcdef\AppData\Local\Temp_ _C.cp38-win_amd64.pyd
这个bug在编译和运行过程中没有产生影响。下面是解决方法
找到.spec文件,加入以下代码,spec文件在项目文件夹,exe生成失败也有。
for d in a.datas: if '_C.cp38-win_amd64.pyd' in d[0]: a.datas.remove(d) break
详细的.spec文件如下
# -*- mode: python ; coding: utf-8 -*- block_cipher = None a = Analysis(['MyTcpServer.py'], pathex=['G:\\yolo'], binaries=[], datas=[], hiddenimports=[], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False) for d in a.datas: if '_C.cp38-win_amd64.pyd' in d[0]: a.datas.remove(d) break pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, [], name='MyTcpServer', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, upx_exclude=[], runtime_tmpdir=None, console=True )
修改配置文件后
pyinstaller run.spec #使用run.spec取代run.py,run是文件名,spec和py是格式
Pyinstaller -F -i chengzi.ico run.py # 指定图标打包,chengzi.ico是图标名称
解释一下其中Pyinstaller的参数:
-F代表制作独立的可执行程序,参数表示覆盖打包,这样在打包时,不管我们打包几次,都是最新的。
-w是指程序启动的时候不会打开命令行。如果不加-w的参数,就会有黑洞洞的控制台窗口出来。但是,在刚才的脚本里我加一行print(‘Hello World!’),那么就不要放-w参数了,不然运行会报错,毕竟Hello World!需要在命令行里打印出来。此外,-w参数在GUI界面时非常有用。