Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Environment variable not accessible with Python with sudo [duplicate]

I've got an issue with my python script

First, I defined an environment variable as

export TEST=test

My Python script is quite easy "test.py"

import os
print os.environ['TEST']

So when I run it with

~ $ python test.py

I've got the expected result test printed out. However, if I run the script with

~ $ sudo python test.py

I've got an KeyError: 'TEST' error.

What have I missed ?

like image 840
GuillaumeA Avatar asked Mar 26 '16 20:03

GuillaumeA


1 Answers

Sudo runs with different environment. To keep current environment use -E flag.

sudo -E python test.py

 -E, --preserve-env
             Indicates to the security policy that the user wishes to preserve their existing environment variables.  The security policy may return an error if the user does not have permission to
             preserve the environment.
like image 175
xiº Avatar answered Nov 05 '22 11:11

xiº