What should I do if I can import a module when I run python, but not when I run sudo python?
For example:
whoami
rose
python
>>> import mymodule
>>>
.
sudo python
>>> import mymodule
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named mymodule
I had run sudo chown -R rose:rose
on the package containing this module.
sudo which python
and which python
both print /usr/bin/python
.
I'm running Linux.
In order to import a module, the directory having that module must be present on PYTHONPATH. It is an environment variable that contains the list of packages that will be loaded by Python. The list of packages presents in PYTHONPATH is also present in sys. path, so will add the parent directory path to the sys.
The __init__.py files are required to make Python treat directories containing the file as packages. This prevents directories with a common name, such as string , unintentionally hiding valid modules that occur later on the module search path.
This is caused by the fact that the version of Python you're running your script with is not configured to search for modules where you've installed them. This happens when you use the wrong installation of pip to install packages.
We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.
The sudo
environment did not contain my PYTHONPATH
, becuase my /etc/sudoers
contains Defaults env_reset
. I simply added Defaults env_keep += "PYTHONPATH"
to /etc/sudoers
and now it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With