How to set environment variables in Python? How to set environment variables in Python? python python

How to set environment variables in Python?


Environment variables must be strings, so use

os.environ["DEBUSSY"] = "1"

to set the variable DEBUSSY to the string 1.

To access this variable later, simply use:

print(os.environ["DEBUSSY"])

Child processes automatically inherit the environment variables of the parent process -- no special action on your part is required.


You may need to consider some further aspects for code robustness;

when you're storing an integer-valued variable as an environment variable, try

os.environ['DEBUSSY'] = str(myintvariable)

then for retrieval, consider that to avoid errors, you should try

os.environ.get('DEBUSSY', 'Not Set')

possibly substitute '-1' for 'Not Set'

so, to put that all together

myintvariable = 1os.environ['DEBUSSY'] = str(myintvariable)strauss = int(os.environ.get('STRAUSS', '-1'))# NB KeyError <=> strauss = os.environ['STRAUSS']debussy = int(os.environ.get('DEBUSSY', '-1'))print "%s %u, %s %u" % ('Strauss', strauss, 'Debussy', debussy)


os.environ behaves like a python dictionary, so all the common dictionary operations can be performed. In addition to the get and set operations mentioned in the other answers, we can also simply check if a key exists. The keys and values should be stored as strings.

Python 3

For python 3, dictionaries use the in keyword instead of has_key

>>> import os>>> 'HOME' in os.environ  # Check an existing env. variableTrue...

Python 2

>>> import os>>> os.environ.has_key('HOME')  # Check an existing env. variableTrue>>> os.environ.has_key('FOO')   # Check for a non existing variableFalse>>> os.environ['FOO'] = '1'     # Set a new env. variable (String value)>>> os.environ.has_key('FOO')True>>> os.environ.get('FOO')       # Retrieve the value'1'

There is one important thing to note about using os.environ:

Although child processes inherit the environment from the parent process, I had run into an issue recently and figured out, if you have other scripts updating the environment while your python script is running, calling os.environ again will not reflect the latest values.

Excerpt from the docs:

This mapping is captured the first time the os module is imported,typically during Python startup as part of processing site.py. Changesto the environment made after this time are not reflected inos.environ, except for changes made by modifying os.environ directly.

os.environ.data which stores all the environment variables, is a dict object, which contains all the environment values:

>>> type(os.environ.data)  # changed to _data since v3.2 (refer comment below)<type 'dict'>


matomo