Reading and writing environment variables in Python?

user749632 picture user749632 · May 12, 2011 · Viewed 386.7k times · Source

My python script which calls many python functions and shell scripts. I want to set a environment variable in Python (main calling function) and all the daughter processes including the shell scripts to see the environmental variable set.

I need to set some environmental variables like this:

DEBUSSY 1
FSDB 1

1 is a number, not a string. Additionally, how can I read the value stored in an environment variable? (Like DEBUSSY/FSDB in another python child script.)

Answer

voithos picture voithos · May 12, 2011

Try using the os module.

import os

os.environ['DEBUSSY'] = '1'
os.environ['FSDB'] = '1'

# Open child processes via os.system(), popen() or fork() and execv()

someVariable = int(os.environ['DEBUSSY'])

See the Python docs on os.environ. Also, for spawning child processes, see Python's subprocess docs.