12
votes

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.

1
Most likely $PYTHONPATH is different, or not even set, for your root user. - Code-Apprentice
@Code-Apprentice I did have to put the module on my $PYTHONPATH, but echo $PYTHONPATH and sudo echo $PYTHONPATH print the same thing. - Rose Perrone
@Code-Apprentice that would be odd. When you run a command with sudo the environment variables are the same. That is for linux, and only if the command is run from the same shell process. - MrAlias
@karthikr I added Defaults env_keep += "PYTHONPATH" to /etc/sudoers and now it works. - Rose Perrone

1 Answers

10
votes

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.