python os.environment_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.

回答1:

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.

回答2:

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)

回答3:

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"]

回答4:

You should assign string value to environment variable.

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

If you want to read or print the environment variable just use

print os.environ["DEBUSSY"]

This changes will be effective only for the current process where it was assigned, it will no change the value permanently. The child processes will automatically inherit the environment of the parent process.

回答5:

What about os.environ["DEBUSSY"] = '1'? Environment variables are always strings.

回答6:

You can use the os.environ dictionary to access your environment variables.

Now, a problem I had is that if I tried to use os.system to run a batch file that sets your environment variables (using the SET command in a **.bat* file) it would not really set them for your python environment (but for the child process that is created with the os.system function). To actually get the variables set in the python environment, I use this script: import re import system import os def setEnvBat(batFilePath, verbose = False): SetEnvPattern = re.compile("set (\w+)(?:=)(.*)$", re.MULTILINE) SetEnvFile = open(batFilePath, "r") SetEnvText = SetEnvFile.read() SetEnvMatchList = re.findall(SetEnvPattern, SetEnvText) for SetEnvMatch in SetEnvMatchList: VarName=SetEnvMatch[0] VarValue=SetEnvMatch[1] if verbose: print "%s=%s"%(VarName,VarValue) os.environ[VarName]=VarValue

回答7:

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: >>> import os >>> os.environ.has_key('HOME') # Check an existing env. variable True >>> os.environ.has_key('FOO') # Check for a non existing variable False >>> 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'

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. Changes to the environment made after this time are not reflected in os.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)

回答8:

When you play with environment variables (add/modify/remove variables), a good practice is to restore the previous state at function completion.

You may need something like the modified_environ context manager describe in this question to restore the environment variables.

Classic usage: with modified_environ(DEBUSSY="1"): call_my_function()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值