Environment Variables in Python
Environment variables are a universal mechanism for conveying configuration information to Unix programs. Let’s look at how to set, get, and list environment variables.
import os
def main():
# To set a key/value pair, use os.environ
# To get a value for a key, use os.environ.get()
# This will return None if the key isn't present in the environment
os.environ['FOO'] = '1'
print("FOO:", os.environ.get('FOO'))
print("BAR:", os.environ.get('BAR'))
# Use os.environ to list all key/value pairs in the environment
# This returns a dictionary of strings in the form KEY: value
# Here we print all the keys
print()
for key in os.environ:
print(key)
if __name__ == "__main__":
main()
Running the program shows that we pick up the value for FOO
that we set in the program, but that BAR
is None.
$ python environment_variables.py
FOO: 1
BAR: None
TERM_PROGRAM
PATH
SHELL
...
FOO
The list of keys in the environment will depend on your particular machine.
If we set BAR
in the environment first, the running program picks that value up.
$ BAR=2 python environment_variables.py
FOO: 1
BAR: 2
...
In Python, we use the os
module to interact with environment variables. The os.environ
object is a dictionary-like object that represents the environment variables. We can set new environment variables by assigning to os.environ['KEY']
, and we can retrieve values using os.environ.get('KEY')
, which returns None
if the key doesn’t exist.
To list all environment variables, we can simply iterate over os.environ
. Each key in this dictionary represents an environment variable name.
Note that changes to os.environ
in a Python program only affect the environment of the current process and its child processes. They do not modify the system environment permanently.