如何在Python中设置环境变量

问题:如何在Python中设置环境变量

我需要在python脚本中设置一些环境变量,并且我希望从python调用的所有其他脚本来查看设置的环境变量。

如果我做

os.environ["DEBUSSY"] = 1`

它抱怨说1必须是字符串。

我还想知道一旦设置好如何在python(在脚本的后半部分)中读取环境变量。

I need to set some environment variables in the python script and I want all the other scripts that are called from python to see the environment variables set.

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.


回答 0

环境变量必须是字符串,因此请使用

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

将变量DEBUSSY设置为字符串1

以后要访问此变量,只需使用:

print(os.environ["DEBUSSY"])

子进程会自动继承父进程的环境变量-无需您执行任何特殊操作。

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 variables of the parent process — no special action on your part is required.


回答 1

您可能需要考虑其他方面的代码健壮性;

当您将整数值的变量存储为环境变量时,请尝试

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

然后为了进行检索,请考虑为避免错误,应尝试

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

可能用“ -1”代替“未设置”

所以,把所有这些放在一起

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)

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)

回答 2

os.environ行为类似于python字典,因此可以执行所有常见的字典操作。除了其他答案中提到的getset操作之外,我们还可以简单地检查键是否存在。键和值应存储为字符串

Python 3

对于python 3,字典使用in关键字而不是has_key

>>> import os
>>> 'HOME' in os.environ  # Check an existing env. variable
True
...

Python 2

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

使用时要注意一件事os.environ

尽管子进程从父进程继承了环境,但是我最近遇到了一个问题,并弄清楚了,如果在运行python脚本时还有其他脚本在更新环境,那么os.environ再次调用将不会反映最新的值

文档摘录:

首次导入os模块时(通常是在Python启动期间作为处理site.py的一部分)捕获了此映射。此时间之后对环境所做的更改不会反映在os.environ中,除非直接修改os.environ进行更改。

os.environ.data 存储所有环境变量的是一个dict对象,其中包含所有环境值:

>>> type(os.environ.data)  # changed to _data since v3.2 (refer comment below)
<type 'dict'>

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. The keys and values should be stored as strings.

Python 3

For python 3, dictionaries use the in keyword instead of has_key

>>> import os
>>> 'HOME' in os.environ  # Check an existing env. variable
True
...

Python 2

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

There is one important thing to note about using os.environ:

Although child processes inherit the environment from the parent process, 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)  # changed to _data since v3.2 (refer comment below)
<type 'dict'>

回答 3

如果我做os.environ [“ DEBUSSY”] = 1,它会抱怨说1必须是字符串。

然后做

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

我也想知道一旦我设置了如何在python(在脚本的后半部分)中读取环境变量。

只需使用os.environ["DEBUSSY"],如

some_value = os.environ["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"]

回答 4

设置变量:

使用键的项目分配方法:

import os    
os.environ['DEBUSSY'] = '1'  #Environ Variable must be string not Int

获取或检查其是否存在,

由于os.environ是一个实例,您可以尝试对象方式。

方法1:

os.environ.get('DEBUSSY') # this is error free method if not will return None by default

将获得'1'作为返回值

方法2:

os.environ['DEBUSSY'] # will throw an key error if not found!

方法3:

'DEBUSSY' in os.environ  # will return Boolean True/False

方法4:

os.environ.has_key('DEBUSSY') #last 2 methods are Boolean Return so can use for conditional statements

to Set Variable:

item Assignment method using key:

import os    
os.environ['DEBUSSY'] = '1'  #Environ Variable must be string not Int

to get or to check whether its existed or not,

since os.environ is an instance you can try object way.

Method 1:

os.environ.get('DEBUSSY') # this is error free method if not will return None by default

will get '1' as return value

Method 2:

os.environ['DEBUSSY'] # will throw an key error if not found!

Method 3:

'DEBUSSY' in os.environ  # will return Boolean True/False

Method 4:

os.environ.has_key('DEBUSSY') #last 2 methods are Boolean Return so can use for conditional statements

回答 5

您应该将字符串值分配给环境变量。

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

如果要读取或打印环境变量,请使用

print os.environ["DEBUSSY"]

此更改仅对分配了当前过程的当前过程有效,不会永久更改该值。子进程将自动继承父进程的环境。

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.


回答 6

os.environ["DEBUSSY"] = '1'呢 环境变量始终是字符串。

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


回答 7

我一直在尝试添加环境变量。我的目标是将一些用户信息存储到系统变量中,以便可以将这些变量用于将来的解决方案,以替代配置文件。但是,下面的代码中描述的方法完全没有帮助。

import os
os.environ["variable_1"] = "value_1"
os.environ["variable_2"] = "value_2"
# To Verify above code
os.environ.get("variable_1")
os.environ.get("variable_2")

这个简单的代码块运行良好,但是,这些变量存在于各自的进程中,因此您将无法在Windows系统设置的环境变量选项卡中找到它们。上面的代码几乎没有达到我的目的。这里讨论这个问题:变量保存问题

os.environ.putenv(key, value)

另一个失败的尝试。因此,最后,我通过模仿包装在os包系统类中的Windows shell命令,成功地将变量保存在窗口环境寄存器中。以下代码描述了此成功尝试。

os.system("SETX {0} {1} /M".format(key, value))

希望对您中的某些人有所帮助。

I have been trying to add environment variables. My goal was to store some user information to system variables such that I can use those variables for future solutions, as an alternative to config files. However, the method described in the code below did not help me at all.

import os
os.environ["variable_1"] = "value_1"
os.environ["variable_2"] = "value_2"
# To Verify above code
os.environ.get("variable_1")
os.environ.get("variable_2")

This simple code block works well, however, these variables exist inside the respective processes such that you will not find them in the environment variables tab of windows system settings. Pretty much above code did not serve my purpose. This problem is discussed here: variable save problem

os.environ.putenv(key, value)

Another unsuccessful attempt. So, finally, I managed to save variable successfully inside the window environment register by mimicking the windows shell commands wrapped inside the system class of os package. The following code describes this successful attempt.

os.system("SETX {0} {1} /M".format(key, value))

I hope this will be helpful for some of you.


回答 8

应该注意的是,如果您尝试将环境变量设置为bash评估,它将不会存储您期望的结果。例:

from os import environ

environ["JAVA_HOME"] = "$(/usr/libexec/java_home)"

这不会像在shell中那样对它求值,因此/Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home您将获得原义表达式,而不是获取路径$(/usr/libexec/java_home)

确保在设置环境变量之前对其进行评估,如下所示:

from os import environ
from subprocess import Popen, PIPE

bash_variable = "$(/usr/libexec/java_home)"
capture = Popen(f"echo {bash_variable}", stdout=PIPE, shell=True)
std_out, std_err = capture.communicate()
return_code = capture.returncode

if return_code == 0:
    evaluated_env = std_out.decode().strip()
    environ["JAVA_HOME"] = evaluated_env
else:
    print(f"Error: Unable to find environment variable {bash_variable}")

It should be noted that if you try to set the environment variable to a bash evaluation it won’t store what you expect. Example:

from os import environ

environ["JAVA_HOME"] = "$(/usr/libexec/java_home)"

This won’t evaluate it like it does in a shell, so instead of getting /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home as a path you will get the literal expression $(/usr/libexec/java_home).

Make sure to evaluate it before setting the environment variable, like so:

from os import environ
from subprocess import Popen, PIPE

bash_variable = "$(/usr/libexec/java_home)"
capture = Popen(f"echo {bash_variable}", stdout=PIPE, shell=True)
std_out, std_err = capture.communicate()
return_code = capture.returncode

if return_code == 0:
    evaluated_env = std_out.decode().strip()
    environ["JAVA_HOME"] = evaluated_env
else:
    print(f"Error: Unable to find environment variable {bash_variable}")

回答 9

您可以使用os.environ字典来访问环境变量。

现在,我遇到的一个问题是,如果我试图用来os.system运行设置环境变量的批处理文件(在**。bat *文件中使用SET命令),那么它实际上不会为您的python环境设置它们(但对于使用该os.system函数创建的子进程)。为了实际获取在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

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

回答 10

当您使用环境变量(添加/修改/删除变量)时,一个好的做法是在函数完成时恢复以前的状态。

您可能需要类似modified_environ上下文管理器的问题来还原环境变量。

经典用法:

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

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