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.
我需要在python脚本中设置一些环境变量,我希望所有其他从python (shell脚本)调用的脚本都是子进程,以便查看环境变量设置。
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.
如果我做操作系统。环境["DEBUSSY"] = 1,它抱怨说1必须是字符串。我还想知道如何在设置之后(在脚本的后面部分)读取python中的环境变量。
8 个解决方案
#1
438
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
将变量DEBUSSY设置为字符串1。要以后访问该变量,只需使用
print os.environ["DEBUSSY"]
Child processes automatically inherit the environment of the parent process -- no special action on your part is required.
子进程自动继承父进程的环境——不需要对您的部分执行特殊操作。
#2
86
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'
可能用'-1'代替'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
16
if i do os.environ["DEBUSSY"] = 1, it complains saying that 1 has to be string.
如果我做操作系统。环境["DEBUSSY"] = 1,它抱怨说1必须是字符串。
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.
我还想知道如何在设置之后(在脚本的后面部分)读取python中的环境变量。
Just use os.environ["DEBUSSY"]
, as in
用操作系统。环境(“德彪西”),如在
some_value = os.environ["DEBUSSY"]
#4
15
You should assign string value to environment variable.
您应该为环境变量分配字符串值。
os.environ["DEBUSSY"] = "1"
操作系统。环境(“德彪西”)= " 1 "
If you want to read or print the environment variable just use
如果您想读取或打印环境变量,只需使用
print os.environ["DEBUSSY"]
打印os.environ(“德彪西”)
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
13
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:
操作系统。环境就像一个python字典,所以所有的通用字典操作都可以执行。除了其他答案中提到的get和set操作外,我们还可以简单地检查键是否存在:
>>> 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.
最近我遇到了一个问题,我发现,如果在运行python脚本时,您有其他脚本更新环境,调用os。环境再次不会反映最新的值。
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模块时捕获的,通常在Python启动时作为处理站点的一部分。在此之后对环境所做的更改没有反映在os中。环境,除了修改os所做的更改。直接环境。
os.environ.data
which stores all the environment variables, is a dict object, which contains all the environment values:
os.environ。存储所有环境变量的数据是一个dict对象,它包含所有的环境值:
>>> type(os.environ.data)
<type 'dict'>
#6
12
What about os.environ["DEBUSSY"] = '1'
? Environment variables are always strings.
什么操作系统。环境(“德彪西”)= ' 1 ' ?环境变量总是字符串。
#7
8
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:
我遇到的一个问题是如果我尝试使用os。运行一个批处理文件来设置环境变量(在**中使用SET命令)。它不会为您的python环境(但是为使用os创建的子进程)设置它们。系统功能)。为了实际得到在python环境中设置的变量,我使用这个脚本:
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
#8
4
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.
您可能需要在这个问题中描述的modified_environmental manager之类的东西来恢复环境变量。
Classic usage:
经典的用法:
with modified_environ(DEBUSSY="1"):
call_my_function()
#1
438
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
将变量DEBUSSY设置为字符串1。要以后访问该变量,只需使用
print os.environ["DEBUSSY"]
Child processes automatically inherit the environment of the parent process -- no special action on your part is required.
子进程自动继承父进程的环境——不需要对您的部分执行特殊操作。
#2
86
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'
可能用'-1'代替'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
16
if i do os.environ["DEBUSSY"] = 1, it complains saying that 1 has to be string.
如果我做操作系统。环境["DEBUSSY"] = 1,它抱怨说1必须是字符串。
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.
我还想知道如何在设置之后(在脚本的后面部分)读取python中的环境变量。
Just use os.environ["DEBUSSY"]
, as in
用操作系统。环境(“德彪西”),如在
some_value = os.environ["DEBUSSY"]
#4
15
You should assign string value to environment variable.
您应该为环境变量分配字符串值。
os.environ["DEBUSSY"] = "1"
操作系统。环境(“德彪西”)= " 1 "
If you want to read or print the environment variable just use
如果您想读取或打印环境变量,只需使用
print os.environ["DEBUSSY"]
打印os.environ(“德彪西”)
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
13
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:
操作系统。环境就像一个python字典,所以所有的通用字典操作都可以执行。除了其他答案中提到的get和set操作外,我们还可以简单地检查键是否存在:
>>> 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.
最近我遇到了一个问题,我发现,如果在运行python脚本时,您有其他脚本更新环境,调用os。环境再次不会反映最新的值。
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模块时捕获的,通常在Python启动时作为处理站点的一部分。在此之后对环境所做的更改没有反映在os中。环境,除了修改os所做的更改。直接环境。
os.environ.data
which stores all the environment variables, is a dict object, which contains all the environment values:
os.environ。存储所有环境变量的数据是一个dict对象,它包含所有的环境值:
>>> type(os.environ.data)
<type 'dict'>
#6
12
What about os.environ["DEBUSSY"] = '1'
? Environment variables are always strings.
什么操作系统。环境(“德彪西”)= ' 1 ' ?环境变量总是字符串。
#7
8
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:
我遇到的一个问题是如果我尝试使用os。运行一个批处理文件来设置环境变量(在**中使用SET命令)。它不会为您的python环境(但是为使用os创建的子进程)设置它们。系统功能)。为了实际得到在python环境中设置的变量,我使用这个脚本:
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
#8
4
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.
您可能需要在这个问题中描述的modified_environmental manager之类的东西来恢复环境变量。
Classic usage:
经典的用法:
with modified_environ(DEBUSSY="1"):
call_my_function()