How to set environment variables in Python

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


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 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 = 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)

if i do os.environ["DEBUSSY"] = 1, it complains saying that 1 has to be string.

Then do

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

I also want to know how to read the environment variables in python(in the later part of the script) once i set it.

Just use os.environ["DEBUSSY"] , as in

some_value = os.environ["DEBUSSY"]
链接地址: http://www.djcxy.com/p/30338.html

上一篇: 暂停命令在.bat脚本中不起作用

下一篇: 如何在Python中设置环境变量