Import error for lxml in python

老子叫甜甜 提交于 2019-12-21 12:19:21

问题


I wrote a script some times ago that contain

from lxml import etree

But, unfortunatly it is not working anymore. In doubt i checked installation with :

sudo apt-get install python-lxml
sudo pip install lxml
sudo apt-get install libxml2-dev
sudo apt-get install libxslt1-dev

I checked if it could be my python version with :

me@pc:~$ python
Python 2.7.3 (default, Sep 14 2012, 14:11:57) 
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import lxml
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named lxml

My os is ubuntu 12.04.1 LTS with Python 2.7.3.

All seems fine. I can't see what could be the problem.

SOLVED:

Finally importing etree with

from xml import etree

Don't know why and if there is a difference but it's working as expected.


回答1:


Your solution cited in edit, which use the xml.etree instead of lxml.etree is not the better way to do it, as these module have known incompatibilities, and mainly because lxml is certainly more optimised.

A good way to make a clean environment available is to use virtualenv :

$ virtualenv myproject
$ cd myproject
$ ./bin/pip install lxml # Repeat this with other dependencies
[wait for download and compiling]

Then, use ./bin/python to execute your script. The advantages of this method are :

  • you can have different versions of dependencies between your system and your project
  • even if you break everything in your virtual environment, you will not compromised the rest of your system
  • you do not need root privileges to make an installation

As a reference, a more powerful but slightly more complex way to achieve this is to use buildout, but it can looks like hunting flies with a bazooka if you just want to execute a simple one-file script.




回答2:


Solved the problem.

It seems that a software that i installed messed out my python path. The python that i was using when calling python in a terminal was the one installed by the software, and the one called by my script was the one installed on my system.

So, i just removed the python path of the software from the path variable of bash.




回答3:


I had this problem when running tests in PyCharm. I could import lxml when using the terminal and virtual environment, but using the same virtual environment to run the tests resulted in the ImportError.

In my case upgrading from lxml 3.3.5 to 4.2.5 fixed the problem.




回答4:


For Python 3.6, it is very tricky.

I have the same problem and try to install the latest version, lxml 3.8. But I still get the error. And then I use lxml 3.7.3, then it is ok.



来源:https://stackoverflow.com/questions/14241685/import-error-for-lxml-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!