Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Not all environment variables present in os.environ

In the python shell, using

import os 
print os.environ 

prints the complete list of environment variables with nothing missing. However when I call the interpreter with a filename:

sudo python file.py 

and use

import os 
print os.environ 

I see that some of the environment variables are missing in the dict.

Why do they behave differently?

Operating system: Ubuntu 14.04

like image 360
dominique Avatar asked Jul 26 '16 06:07

dominique


People also ask

How do I set environ variables in Python os?

To set and get environment variables in Python you can just use the os module: import os # Set environment variables os. environ['API_USER'] = 'username' os. environ['API_PASSWORD'] = 'secret' # Get environment variables USER = os.

How do I get all environment variables?

To list all the environment variables, use the command " env " (or " printenv "). You could also use " set " to list all the variables, including all local variables.

Where are Python environment variables stored?

Use .env File to Store Environment Variablesenv file at the root of the project directory and put the credential in the file.


2 Answers

I saw this happen when ENV Vars were not set using export in bash, so they were not propagating to the python script.

like image 164
storm_m2138 Avatar answered Nov 15 '22 09:11

storm_m2138


I realised that the difference was because I was using sudo during the execution for the second where the environment was not preserved. I need to add those environment variables to my sudoers file or preserve them during execution.

like image 20
dominique Avatar answered Nov 15 '22 10:11

dominique