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
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.
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.
Use .env File to Store Environment Variablesenv file at the root of the project directory and put the credential in the file.
I saw this happen when ENV Vars were not set using export in bash, so they were not propagating to the python script.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With