Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (47.6k points)

I need to set some environment variables in the python script and I want all the other scripts that are called from python (shell scripts) which will be child process to see the environment variables set. The value is a number.

If I do os.environ["DEBUSSY"] = 1, it complains saying that 1 has to be a string. I also want to know how to read the environment variables in python (in the later part of the script) once I set it.

2 Answers

0 votes
by (106k points)

By following the mentioned way you can set the environment variable in Python:-

Your environment variables must be strings, below is the code that you can use to set the environment variable:-

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

The above code is used to set the variable DEBUSSY to the string 1.

After setting DEBUSSY to environment variable it will be accessed by using the following piece of code:-


You asked about child process, so the child processes automatically inherit the environment variables of the parent process -- no special action on your part is required.

0 votes
by (20.3k points)

For code robustness, you can consider some further aspects like, when you're storing an integer-valued variable as an environment variable, then try using this

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

For retrieval, consider that to avoid errors, you can try using the below code:

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

possibly substitute '-1' for 'Not Set'

so, to put that all together

myintvariable = 1

os.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)

Browse Categories