Python模块导入错误

1 投票
4 回答
2000 浏览
提问于 2025-04-17 03:06

我刚刚在Python中安装了lxml,这是用来解析XML文件的工具。我在用TextMate作为我的开发环境。问题是,当我尝试导入lxml时,使用的代码是 (from lxml import entree),结果出现了

ImportError:'没有名为lxml的模块'

但是当我在Terminal(终端)中使用时,一切都正常

Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from lxml import etree
>>> root=etree.element("root")
>>> root=etree.Element("root")
>>> print (root.tag)
root
>>> root.append(etree.Element("child1"))
>>> child2 = etree.SubElement(root, "child2")
>>> child3 = etree.SubElement(root, "child3")
>>> print (etree.tostring(root,pretty_print=True))
<root>
  <child1/>
  <child2/>
  <child3/>
</root>

这真是有点奇怪。这和TextMate有关系吗?

请给点建议!

4 个回答

1

很可能TextMate使用的PYTHONPATH和你在终端里用的不同。因为我不是TextMate的用户,所以不能给你具体的帮助,但这应该能给你一些提示,让你找到问题所在。

2

你需要在TextMate的设置里定义一些环境变量,特别是'TM_PYTHON'这个变量,它需要指向你的Python程序的路径。

要找出你正在使用哪个Python版本,你可以在终端里输入'which python'。

3

这很可能意味着你的电脑上安装了多个Python版本,而TextMate和终端默认使用的是不同的版本。

一个解决办法是:在你的Python文件中,可以添加一个指令,来指定你想使用的Python版本和可执行文件:

#!/usr/local/bin/python
# Even thought standard python is in /usr/bin/python, here we want another ...

撰写回答