在OS X 10.7上安装lxml遇到问题请帮忙
我一直在努力让 from lxml import etree
这个命令能正常工作(顺便说一下,import lxml
是没问题的)。但是我遇到了这个错误:
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site- packages/lxml/etree.so, 2): Symbol not found: _htmlParseChunk
Referenced from: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/lxml/etree.so
Expected in: flat namespace
in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/lxml/etree.so
我用 pip 安装了 lxml,还用 homebrew 重新安装了 libxml2,确保它的架构是对的(我觉得是这样)……有没有人知道怎么解决这个问题或者怎么诊断一下?我用的是 64 位的 Python。
1 个回答
12
lxml
对于它所使用的第三方库有点挑剔,通常需要比苹果提供的更新版本。建议你查看并按照这里的说明,从源代码在 Mac OS X 上构建 lxml
,包括构建它自己的静态链接库。这样应该能解决问题。(我有点惊讶 homebrew 还没有 lxml 的配方。)
更新:根据你评论中有限的信息,很难确定到底发生了什么。我怀疑你使用的 Python 版本可能不是你认为的那个。安装 lxml 的方法有很多,这也是问题的一部分:选择太多了。与其尝试调试你的环境,不如直接给你一个在 10.7 上使用苹果自带的系统 Python 2.7 安装 lxml 的简单方法。
$ sudo STATIC_DEPS=true /usr/bin/easy_install-2.7 lxml
然后你应该可以这样使用 lxml.etree
:
$ /usr/bin/python2.7
Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from lxml import etree
>>> etree.__file__
'/Library/Python/2.7/site-packages/lxml-2.3.1-py2.7-macosx-10.7-intel.egg/lxml/etree.so'
>>>
不过我注意到 lxml
的静态构建过程并不会生成一个可用的通用版本。在安装 lxml
时,你可能会看到这样的消息:
ld: warning: ignoring file /private/tmp/easy_install-83mJsV/lxml-2.3.1/build/tmp/libxml2/lib/libxslt.a, file was built for archive which is not the architecture being linked (i386)
假设你机器上的默认架构是 64 位,如果你尝试以 32 位模式运行:
$ arch -i386 /usr/bin/python2.7
Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:06)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from lxml import etree
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: dlopen(/Library/Python/2.7/site-packages/lxml-2.3.1-py2.7-macosx-10.7-intel.egg/lxml/etree.so, 2): Symbol not found: _htmlParseChunk
Referenced from: /Library/Python/2.7/site-packages/lxml-2.3.1-py2.7-macosx-10.7-intel.egg/lxml/etree.so
Expected in: flat namespace
in /Library/Python/2.7/site-packages/lxml-2.3.1-py2.7-macosx-10.7-intel.egg/lxml/etree.so
>>> ^D
那么你最初报告的错误信息就会出现!所以这个问题的根本原因似乎是 lxml
构建的静态库(libxml2
等)并不是通用的。只要你不需要在 32 位进程中使用 lxml
(大多数情况下不太可能),这应该不会成为问题。很可能你最初使用的 Python 是仅支持 32 位的;这和你报告的其他一些信息是一致的。