Import error for lxml in python

I wrote a script several times ago that contain

from lxml import etree 

But unfortunately, it no longer works. In doubt, I checked the 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 this 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.

Everything seems beautiful. I do not see what could be the problem.

SOLVE:

Finally, importing etree with

 from xml import etree 

I don’t know why and if there is a difference, but it works as expected.

+7
source share
3 answers

Solved a problem.

It seems that the software I installed messed up my python path. The python that I used when calling python in the terminal was the one that was installed by the software, and the one that called my script was the one that was installed on my system.

So, I just deleted the python software path from the bash path variable.

+4
source

Your edit solution, which uses xml.etree instead of lxml.etree, is not the best way to do this, since this module knew incompatibilities , and mainly because lxml is certainly more optimized .

A good way to create a clean environment 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 the script. The advantages of this method are as follows:

  • You may have different versions of the dependencies between your system and your project.
  • even if you violate everything in your virtual environment, you will not jeopardize the rest of your system.
  • you do not need root privileges to install

As a reference, a more powerful but slightly more complicated way to do this is to use buildout , but it may look like hunting flies with bazooka if you just want to run a simple single-file script.

+6
source

For Python 3.6, this is very difficult.

I have the same problem and am trying to install the latest version, lxml 3.8. But I still get the error. And then I use lxml 3.7.3, then this is normal.

-one
source

All Articles