我为什么会遇到这个ImportError?

7 投票
2 回答
10386 浏览
提问于 2025-04-17 20:32

我有一个用 tkinter 做的应用程序,我想通过 py2exe 把它打包成一个 .exe 文件。

在设置文件里,我已经把 lxmlurlliblxml.htmlastmath 加进去了。

当我在命令提示符(CMD)里运行 python setup.py py2exe 时,打包过程很顺利。然后我去到它创建的 dist 文件夹,运行那个 .exe 文件。

但是,当我运行这个 .exe 文件时,弹出了一个窗口。this
(来源: gyazo.com)

接着我打开了 Trader.exe.log 文件,里面的内容是这样的;

Traceback (most recent call last):
  File "Trader.py", line 1, in <module>
  File "lxml\html\__init__.pyc", line 42, in <module>
  File "lxml\etree.pyc", line 12, in <module>
  File "lxml\etree.pyc", line 10, in __load
  File "lxml.etree.pyx", line 84, in init lxml.etree (src\lxml\lxml.etree.c:190292)
ImportError: cannot import name _elementpath

这里有一个我的 setup.py 文件的副本,请查看

请帮我找出问题所在。提前谢谢你们。

2 个回答

1

Py2exe在这个页面上对这个错误进行了说明:http://www.py2exe.org/index.cgi/WorkingWithVariousPackagesAndModules

他们还提供了一个有效的解决方案。

7

看起来 py2exe 没有意识到它应该包含 lxml._elementpath 这个模块,因为这个模块是由 lxml.etree 条件性地导入的。你可以在你的 setup.py 文件中,使用 includes 这个关键字参数,明确告诉它要包含这个模块。

setup(
    options={'py2exe': {"includes": ["lxml._elementpath"]}}
)

撰写回答