Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't import module when using root user [duplicate]

Tags:

python

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.

like image 562
Rose Perrone Avatar asked Aug 17 '14 03:08

Rose Perrone


People also ask

How do I import a module from the root directory?

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.

Why do I need __ init __ py?

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.

Why won't Python recognize my module?

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.

How can I import modules if file is not in same directory?

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.


1 Answers

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.

like image 61
Rose Perrone Avatar answered Nov 13 '22 02:11

Rose Perrone