使用Poetry管理依赖时,PyInstaller打包exe遇termcolor依赖缺失问题
问题:PyInstaller打包含termcolor的Python脚本时出现ModuleNotFoundError
在Windows 10 Pro系统中,用Poetry创建环境并安装termcolor后,在Poetry Shell里运行脚本完全正常,但用pyinstaller --onefile main.py打包生成的exe文件运行时,会抛出ModuleNotFoundError: termcolor错误。
相关代码与配置
main.py
from termcolor import cprint def main() -> None: cprint('Hello', 'red') if __name__ == '__main__': main()
环境搭建命令
poetry new test poetry add termcolor
打包命令
pyinstaller --onefile main.py
生成的main.spec文件
a = Analysis( ['main.py'], pathex=['.', 'C:\Users\... path to ...\site-packages'], binaries=[], datas=[], hiddenimports=[], hookspath=[], hooksconfig={}, runtime_hooks=[], excludes=[], noarchive=False, optimize=0, ) pyz = PYZ(a.pure) exe = EXE( pyz, a.scripts, [], exclude_binaries=True, name='main', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, console=True, disable_windowed_traceback=False, argv_emulation=False, target_arch=None, codesign_identity=None, entitlements_file=None, ) coll = COLLECT( exe, a.binaries, a.datas, strip=False, upx=True, upx_exclude=[], name='main', )
问题原因
- PyInstaller的依赖扫描机制并非完美,对于termcolor这类结构简单的库,有时无法自动检测到它的导入关系。
- spec文件中填写的site-packages路径存在格式问题(Windows路径的反斜杠需要转义,否则会被当作转义字符处理),导致PyInstaller无法正确找到依赖位置。
- 可能未在Poetry的虚拟环境中运行PyInstaller,导致它扫描的是全局Python环境而非项目虚拟环境。
解决方法
方法1:打包时显式指定隐藏导入
直接在打包命令中通过--hidden-import参数告诉PyInstaller要包含termcolor:
pyinstaller --onefile --hidden-import termcolor main.py
方法2:修改spec文件添加隐藏导入
编辑生成的main.spec文件,在Analysis的hiddenimports列表中加入termcolor,同时修正路径格式(用原始字符串r''包裹Windows路径):
a = Analysis( ['main.py'], pathex=['.', r'C:\Users\... path to ...\site-packages'], binaries=[], datas=[], hiddenimports=['termcolor'], # 添加这一行 hookspath=[], hooksconfig={}, runtime_hooks=[], excludes=[], noarchive=False, optimize=0, )
然后用spec文件重新打包:
pyinstaller main.spec
方法3:在Poetry虚拟环境中运行PyInstaller
先激活Poetry Shell,确保PyInstaller使用的是项目虚拟环境的依赖:
poetry shell pyinstaller --onefile main.py
内容的提问来源于stack exchange,提问作者Psionman
相关产品推荐
相关产品推荐

