1

Since I need to create a raw socket inside my python code, I need to run it as root. When I do that I found out that my imported modules are no longer supported somehow:

`No module named foo`

(I used to run my scripts as sh myScript.sh option1 where my python script.py is called from within myScript.sh).

Now I try: sudo fullPathName/myScript.py and I also included in its beginning

#!/usr/bin/python and make it executable by chmod +x myScript.py

still having the no No module named foo issue.

NELOUNI
  • 593
  • 2
  • 6
  • 14
  • Where is `script.py`? Does your non-root user have `PYTHONPATH` environment variable set? – Lev Levitsky Jun 30 '14 at 14:46
  • `/bin/python` is probably the wrong path for most systems. – FatalError Jun 30 '14 at 14:46
  • actually my script.py is in some directory of my own. My non-root has environment variable set PYTHONPATH. @FatalError: sorry I am using "/usr/bin/python" and I checked that python executable is there – NELOUNI Jun 30 '14 at 14:50
  • Then you probably need it to be set when you run the script as root, as well. – Lev Levitsky Jun 30 '14 at 14:52
  • Please use virtualenv to install external libraries, so you can maintain the packages and modules in better manner: http://opensourcehacker.com/2012/09/16/recommended-way-for-sudo-free-installation-of-python-software-with-virtualenv/ (virtualenv works for root too, doesn't need PYTHONPATH, please use it to avoid installing modules and packages directly to system folders) – Mikko Ohtamaa Jun 30 '14 at 14:53
  • @Mikko but `sudo` is not used for installation here. – Lev Levitsky Jun 30 '14 at 14:54
  • How can I do that please, (Need it to be set when I run the script as root): apart from my ~/.bashrc is there an equivalent for me when I run scripts as root for example ? – NELOUNI Jun 30 '14 at 14:55
  • @LevLevitsky Does not matter – Mikko Ohtamaa Jun 30 '14 at 14:55

1 Answers1

3

You need to preserve PYTHONPATH when running commands with sudo. sudo can be configured to retain certain environment variables via the sudoers file.

So you can run visudo (as root) and add something like this:

Defaults env_keep += "PYTHONPATH"

Then save the changes.

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175