使用py2exe打包Python脚本时遭遇lxml相关ImportError问题求助
问题现象
打包过程无警告或错误,但运行生成的mdf2mat.exe时出现以下错误:
Traceback (most recent call last):
File "", line 259, in load_module
File "", line 15, in
File "", line 13, in __load
ImportError: (cannot import name _elementpath) 'C:\CAD\Workspace\username\dev-env\dist\lxml.etree.pyd'During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "", line 259, in load_module
File "", line 15, in
File "", line 11, in __load
...
File "", line 627, in _load_backward_compatible
File "", line 261, in load_moduleKeyError: 'lxml.objectify'
执行命令:
mdf2mat.exe C:\CAD\username\usefulScripts\dev-folder\dosingFromCANape.mdf
业务脚本代码
import mdfreader import sys fileIn = sys.argv[1] mdfFile = mdfreader.Mdf(fileIn) mdfFile.export_to_matlab()
原打包配置代码
py2exe.freeze(console={"C:\CAD\Workspace\username\dev-env\mdf2mat.py"})
py2exe官方针对lxml的提示
if missing _elementhpath, either pull whole lxml library in packages=..., or put "from lxml import _elementhpath as _dummy" somewhere in code; in both cases also pull gzip in packages=...
具体解决步骤
方法一:通过打包配置直接指定需要包含的库
修改打包代码,补充packages参数,将lxml和gzip明确纳入打包范围(同时修正原代码中console参数的格式错误,应为列表而非字典):
py2exe.freeze( console=["C:\CAD\Workspace\username\dev-env\mdf2mat.py"], packages=["lxml", "gzip"] )
方法二:脚本添加强制导入语句+打包配置补全依赖
- 在业务脚本
mdf2mat.py开头添加一行仅用于打包识别的导入代码:
from lxml import _elementpath as _dummy # 让py2exe识别到该依赖 import mdfreader import sys # 后续业务代码不变 fileIn = sys.argv[1] mdfFile = mdfreader.Mdf(fileIn) mdfFile.export_to_matlab()
- 修改打包代码,将
gzip加入打包范围:
py2exe.freeze( console=["C:\CAD\Workspace\username\dev-env\mdf2mat.py"], packages=["gzip"] )
任选一种方法重新执行打包,生成的exe即可正常运行。
内容的提问来源于stack exchange,提问作者Ferro Luca

