How to ignore python module in ~/.local/lib/python2.7/site-packages?

7.5k views Asked by At

I have a python package dateutil in the ~/.local/lib/python2.7/site-packages directory as well as one in /usr/lib/python2.7/dist-packages/dateutil. When I try to run an executable from kalibr (a camera calibration tool, I downloaded the CDE), rrule.py from the dateutil package in ~/.local/lib/python2.7/site-packages throws an error "ImportError: No module named fractions". I can get kalibr running, by removing said dateutil package (s.t. it uses the one in /usr/lib/python2.7/dist-packages/dateutil) but I fear that this will have some implications on other projects.

So I figured that the basic problem here is that python prefers the dateutil package in ~/.local/lib/python2.7/site-packages over the one in /usr/lib/python2.7/dist-packages/dateutil.

How can I make python prefer the latter one?

(I am using Ubuntu 16.04)

2

There are 2 answers

0
yorodm On

See the answers here about changing the PYTHONPATH and the default module search order. You should also check your script to see if it modifies either PYTHONPATH or sys.path.

0
Gilles 'SO- stop being evil' On

I don't think there's a way to choose which directory to load packages from on a per-package basis, but you can change the order in which Python looks for packages. The order is reflected in sys.path. The default package search path is influenced by site-specific files, but mostly it's:

  1. The current directory.
  2. Directories listed in the PYTHONPATH environment variable.
  3. The standard library that comes with Python itself.
  4. The dist-packages directory under ~/.local (the user site-packages directory), which is where pip install --user installs things. You can change the path to this directory by setting the environment variable PYTHONUSERBASE and disable it completely by setting PYTHONNOUSERSITE to a non-empty value.
  5. The dist-packages directory under /usr/local, which is where pip install installs things.

So if a directory needs to be traversed first, you can put it in PYTHONPATH. In your case, there's a good chance that you can just disable ~/.local to run kalibr.

env PYTHONNOUSERSITE=1 kalibr

To see the package search path, run

python -m site

(All of this applies to Python3 as well.)

(Generally, preferring packages under ~/.local to packages under /usr is the right thing. Ideally, packages would always be backward compatible, and if you ran into an incompatibility, you'd just install the latest version under ~/.local with pip install --user. But in the real world, this doesn't always work out.)