2

我正在尝试使用 Python 的内置 xml.etree.ElementTree 类构建一个使用一些 xml 数据的应用程序。当我从命令行运行时它可以正常工作,但是当我构建它时,我得到一个错误“ImportError: No module etree.ElementTree”。我猜这是因为我没有正确导入该模块,但我无法弄清楚如何。当我使用“includes”或“packages”指令时,py2app 会抱怨同样的错误,当我特别指定 package_dir (/System/Library/...) 时,它会编译,但仍然给我错误。我提供了一个简短的例子来说明这个问题。

macxml.py

from xml.etree.ElementTree import ElementTree

if __name__ == '__main__':
    tree = ElementTree()
    print tree.parse('lib.xml')

这应该打印出“< Element Library at xxxxxx>”,其中 Library 是根名称。

安装程序.py

from setuptools import setup

setup(name="Mac XML Test",
      app=['macxml.py'],
     )

使mac应用程序利用这个库的正确方法是什么?

Python 2.6.4

Mac OS X 10.6.2

编辑:我也在另一台 Mac (PPC 10.5.8) 上使用 Python 2.6.2 进行了尝试,并取得了相同的结果。

4

3 回答 3

1

在重新安装和更新macholib、modulegraph、py2app和setuptools都无济于事后,我稍微挖掘了一下,在modulegraph模块中发现了以下错误:

graphmodule.find_modules.find_modules(includes=['xml.etree'])
Traceback (most recent call last):
    File "<stdin>", line 1 in <module>
    File ".../modulegraph/find_modules.py", line 255 in find_modules
    File ".../modulegraph/find_modules.py", line 182 in find_needed_modules
    File ".../modulegraph/modulegraph.py", line 401 in import_hook
    File ".../modulegraph/modulegraph.py", line 464 in load_tail
ImportError: No module named xml.etree

所以我对load_tailandimport_hook函数进行了更多的研究,发现由于某种原因它正确地导入了 xml 包,但随后又去旧安装的 _xmlplus 寻找 etree 子包(它当然找不到)。删除 _xmlplus 包消除了错误,我能够让应用程序使用以下 setup.py 文件:

from setuptools import setup
import xml.etree.ElementTree

setup(name="Mac XML Test",
      app=['macxml.py'],
      options={'py2app': {'includes': ['xml.etree.ElementTree']}},
      data_files=[('', ['lib.xml'])]
     )

输出显示在控制台中。

于 2010-02-02T14:28:58.477 回答
1

由于评论没有很好的格式,

在 find_modules.py 我改变了

REPLACEPACKAGES = {
    '_xmlplus':     'xml',
}

REPLACEPACKAGES = {
    #'_xmlplus':     'xml',
}

并且 xml 导入有效。

于 2011-01-07T16:57:56.873 回答
0

如果您使用的是 macports(或 fink 等),请确保py2app使用正确的解释器。您可能必须安装新版本才能使用 2.6.x(在 OS X 10.5 上,py2app使用 2.4.x)。

如果这不起作用,我解决路径问题的步骤是:

  1. 启动您的代码(或py2app)使用的 python 解释器(您绝对确定吗??尝试which python
  2. import sys; print sys.path

如果步骤 2. 为您提供了/System/Library..someotherpythonversion代码中的路径,则在错误的解释器中运行。

于 2010-02-01T19:12:45.780 回答