PyInstaller设置onefile=True仍生成文件夹问题求助
解决PyInstaller onefile=True仍生成文件夹的问题
问题出在你的spec文件中同时保留了COLLECT代码块——当设置onefile=True时,COLLECT是多余的,它会强制生成包含多文件的文件夹结构,覆盖单文件打包的配置。
修复步骤:
- 修改main.spec文件:删除整个
COLLECT代码块,修改后的spec文件如下:
# -*- mode: python ; coding: utf-8 -*- block_cipher = None a = Analysis( ['main.py', 'ui_interface.py', 'utilities.py', 'data.py'], pathex=[], binaries=[], datas=[('MainMenu.ui', '.'), ('style.json', '.'), ('resources_rc.py', '.')], hiddenimports=[], hookspath=[], hooksconfig={}, 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, [], exclude_binaries=True, name='D&PO UIB', debug=True, bootloader_ignore_signals=False, strip=False, upx=True, console=False, disable_windowed_traceback=False, argv_emulation=False, target_arch=None, codesign_identity=None, entitlements_file=None, onefile=True, )
- 重新执行打包命令:
pyinstaller main.spec
- 获取单文件可执行程序:打包完成后,单文件
D&PO UIB.exe会生成在dist目录下。
额外注意事项
使用onefile模式时,程序运行会自动将依赖的资源文件(如MainMenu.ui、style.json)解压到系统临时目录。如果你的代码中直接使用相对路径读取这些文件,需要调整为从临时目录读取,可通过sys._MEIPASS获取临时路径:
import sys import os def get_resource_path(relative_path): try: # 打包后的临时路径 base_path = sys._MEIPASS except Exception: # 开发环境下的路径 base_path = os.path.abspath(".") return os.path.join(base_path, relative_path) # 读取资源文件示例 ui_path = get_resource_path("MainMenu.ui")
内容的提问来源于stack exchange,提问作者Fares
相关产品推荐
相关产品推荐

