lxml 已安装,但无法在 Windows 上运行

lxml installed, but not working on Windows

我需要根据 XSD 验证 XML 文件。为此,我想使用 lxml library。问题是,即使我有 from lxml import etree 并且已将 lxml 安装到 C:\Python33\Lib\site-packages\lxml\,我仍然收到错误

Traceback (most recent call last):
  File "C:\Users\asmithe\Documents\dev1\TestParse.py", line 3, in <module>
    from lxml import etree as ET_l
ImportError: No module named lxml

为什么会这样,我该如何解决?我尝试将 C:\Python33\Lib\site-packages\lxml\ 添加到 PATH 变量,但没有帮助。我使用 PIP 安装了 lxml。

更新:当我通过交互式终端 运行 脚本时(即在 cmd 中键入 python),它可以 import lxml

这是一个简单的脚本

from lxml import etree

def main():
    print('hi')


if __name__ == "__main__":
    main()

我在cmd里做

C:\Users\dev1\Documents\test>python
Python 3.3.5 (v3.3.5:62cf4e77f785, Mar  9 2014, 10:35:05) [MSC v.1600 64 bit (AM
D64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from lxml import etree
>>>
>>> def main():
...     print('hi')
...
>>>
>>> if __name__ == "__main__":
...     main()
...
hi
>>> exit()

但是如果我尝试 运行 它

> ImportLxml.py

然后我得到

C:\Users\dev1\Documents\test>ImportLxml.py
Traceback (most recent call last):
  File "C:\Users\dev1\Documents\XML test\TestImport.py", line 1, in <module>

    from lxml import etree
ImportError: No module named lxml

这里是 PATH 环境变量中的所有 pythonic 条目

C:\Python33\;
C:\Python33\Scripts;
C:\Python33\Lib\site-packages\lxml\
%ARCGISINSALLDIR%\arcpy;

Python Launcher for Windows 配置为默认使用 3.3.5:

py -3

或者 -- 假设您在上次安装 Python 时选择安装 Python Launcher -- begin your script with a shebang which the Python Launcher will recognize as requesting Python 3:

#! python3

如果您在安装 Python 3.3 时决定不为 Windows 安装 Python 启动器,请参阅 the install documentation 了解手动步骤:

Associate the correct file group with .py scripts:

assoc .py=Python.File

Redirect all Python files to the new executable:

ftype Python.File=C:\Path\to\pythonw.exe "%1" %*

这可用于将 Python.File 的类型配置为您选择的 Python 解释器,即。对于 3.3.5。 (作为一个好的做法,Python.File 应该指向 py.exepython.exe;上面的 pythonw.exe 示例是直接引用文档,但仍然是一个不好的做法).


或者,如果您的磁盘上有 py.exe(与 Python 3.3 一起安装)但未被使用,您可以稍微修改这些指令:

Associate the correct file group with .py scripts:

assoc .py=Python.File

Redirect all Python files to the new executable:

ftype Python.File=C:\Path\to\py.exe "%1" %*

...再次调整路径以适合您的安装位置 Python 3.3.x.