0

I am trying to access an environment variable from a python process. I exported it like export var=value. This works fine for the command pyton program.py but not for sudo python program.py. How can I make sure the process can access the environment variable if it is started with sudo?

3

The default security policy for sudo normally prevents it from inheriting environment variables. However unless the particular variable is explicitly denied in your sudoers file, you should be able to allow it by specifying the -E option to sudo, e.g.

$ VAR="value" python -c 'import os; print os.environ.get("VAR")'
value
$ 
$ VAR="value" sudo python -c 'import os; print os.environ.get("VAR")'
None
$ 
$ VAR="value" sudo -E python -c 'import os; print os.environ.get("VAR")'
value
$ 

See man sudo

   -E          The -E (preserve environment) option indicates to the
               security policy that the user wishes to preserve their
               existing environment variables.  The security policy may
               return an error if the -E option is specified and the user
               does not have permission to preserve the environment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.