Search code examples
pythonpipcondasudo

Python conda env does not contain local package when using sudo


I am using a conda environment and some local packages which are installed using pip install -e.

Sometimes I need to run a script as root. When doing so I explicitly use the conda environment, but it does not find my local packages. When using without sudo, everything is working fine.

$ /path/to/env/bin/python -c "import my_module" --> works fine
$ sudo /path/to/env/bin/python -c "import my_module"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ModuleNotFoundError: No module named 'my_module'

I have also tried persisting the environment like this:

$ sudo -E /path/to/env/bin/python -c "import my_module"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ModuleNotFoundError: No module named 'my_module'

Setup:

  • Ubuntu 18.04
  • python 3.7.10

Solution

  • Python (or Anaconda in your case) has few different environments on your computer, when installing packages as a user they are probably installed on ~/.local/python/... and when installing as root they are installed on /var/lib/python/....

    When you are running python as a user and importing a package it we'll look in several places including the local directory.
    But when running python as root it won't look in these places..

    The most simple solution is to install these packages using sudo, or start using venv which is highly more recommended.