17

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.

Rose Perrone
  • 61,572
  • 58
  • 208
  • 243

1 Answers1

14

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.

Rose Perrone
  • 61,572
  • 58
  • 208
  • 243
  • 11
    Actually, did you also try sudo -E -H options? This will preserve your environment variables... if this is not a risk for you to use it's the easier way. – Mayou36 Oct 09 '16 at 16:36
  • 3
    Mayou36 is correct however the -H option sets the HOME environment variable to what is in the password database entry. In my case sudo -E by itself was sufficient to retain the PYTHONPATH and allow the library, in my case, 'uinput' to be used. – James Oct 29 '20 at 00:40
  • @Mayou36 Please post that as an answer – endolith Jan 17 '21 at 04:17
  • 2
    Neither option worked for me – bart cubrich Dec 02 '21 at 17:35