如何使用Pyinstaller 生成整包可执行文件
如何使用Pyinstaller 生成整包可执行文件
1、安装 PyInstaller
pip install pyinstaller
2、修改代码以正确加载资源文件
使用 sys._MEIPASS 访问打包后的资源文件
在代码中,通过 sys._MEIPASS 获取资源文件的路径。例如:
import sys
import os
def resource_path(relative_path):
""" 获取资源的绝对路径 """
if hasattr(sys, '_MEIPASS'):
# 打包后的资源路径
base_path = sys._MEIPASS
else:
# 开发时的资源路径
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
3、使用 PyInstaller 打包
pyinstaller --onefile --add-data “data/;data" --add-data "config/;config” main.py
4、查找生成的可执行文件
打包完成后,生成的可执行文件会出现在 dist 目录下
dist/main.exe
注意事项:
1、隐藏控制台窗口:如果你的程序是图形界面应用,可以使用 --noconsole 参数隐藏控制台窗口:
pyinstaller --onefile --noconsole --add-data “data/;data" --add-data "config/;config” main.py
2、有时 PyInstaller 无法自动检测到某些模块的依赖关系。你可以通过 --hidden-import 参数显式指定需要导入的模块。对于 json 模块,可以尝试
1、pyinstaller --onefile --hidden-import=json your_script.py
2、pyinstaller --onefile --hidden-import=json --hidden-import=missing_module1 --hidden-import=missing_module2 your_script.py
3、跨平台打包不一致
最终PyInstaller的打包语句为:
pyinstaller --onefile --add-data “data/;data" --add-data "config/;config” --hidden-import=json --hidden-import=missing_module1 --hidden-import=missing_module2 your_script.py