如何在Python中使环境变量更改?

时间:2021-07-08 11:48:35

From what I've read, any changes to the environment variables in a Python instance are only available within that instance, and disappear once the instance is closed. Is there any way to make them stick by committing them to the system?

根据我的阅读,Python实例中对环境变量的任何更改仅在该实例中可用,并在实例关闭后消失。是否有任何方法可以通过将它们提交给系统来使它们坚持下去?

The reason I need to do this is because at the studio where I work, tools like Maya rely heavily on environment variables to configure paths across multiple platforms.

我需要这样做的原因是因为在我工作的工作室,像Maya这样的工具在很大程度上依赖于环境变量来配置跨多个平台的路径。

My test code is

我的测试代码是

import os
os.environ['FAKE'] = 'C:\\'

Opening another instance of Python and requesting os.environ['FAKE'] yields a KeyError.

打开另一个Python实例并请求os.environ ['FAKE']会产生KeyError。

NOTE: Portability will be an issue, but the small API I'm writing will be able to check OS version and trigger different commands if necessary.

注意:可移植性将是一个问题,但我正在编写的小API将能够检查操作系统版本并在必要时触发不同的命令。

That said, I've gone the route of using the Windows registry technique and will simply write alternative methods that will call shell scripts on other platforms as they become requirements.

也就是说,我已经走了使用Windows注册表技术的路线,并且只会编写替代方法,这些方法将在其他平台上调用shell脚本,因为它们成为需求。

11 个解决方案

#1


Under Windows it's possible for you to make changes to environment variables persistent via the registry with this recipe, though it seems like overkill.

在Windows下,您可以使用此配方通过注册表对环境变量进行持久更改,尽管它看起来有点过分。

To echo Brian's question, what are you trying to accomplish? There is probably an easier way.

为了回应Brian的问题,你想要完成什么?可能有一种更简单的方法。

#2


make them stick by committing them to the system?

通过将它们提交给系统来使它们坚持下去?

I think you are a bit confused here. There is no 'system' environment. Each process has their own environment as part its memory. A process can only change its own environment. A process can set the initial environment for processes it creates.

我觉得你在这里有点困惑。没有“系统”环境。每个进程都有自己的环境作为其内存的一部分。流程只能改变自己的环境。进程可以为其创建的进程设置初始环境。

If you really do think you need to set environment variables for the system you will need to look at changing them in the location they get initially loaded from like the registry on windows or your shell configuration file on Linux.

如果您确实认为需要为系统设置环境变量,则需要在最初加载的位置更改它们,例如Windows上的注册表或Linux上的shell配置文件。

#3


You can using SETX at the command-line.

您可以在命令行中使用SETX。

By default these actions go on the USER env vars. To set and modify SYSTEM vars use the /M flag

默认情况下,这些操作会在USER env vars上进行。要设置和修改SYSTEM变量,请使用/ M标志

import os
env_var = "BUILD_NUMBER"
env_val = "3.1.3.3.7"
os.system("SETX {0} {1} /M".format(env_var,env_val))

#4


I don't believe you can do this; there are two work-arounds I can think of.

我不相信你能做到这一点;我能想到两种解决方法。

  1. The os.putenv function sets the environment for processes you start with, i.e. os.system, popen, etc. Depending on what you're trying to do, perhaps you could have one master Python instance that sets the variable, and then spawns new instances.

    os.putenv函数为你开始的进程设置环境,即os.system,popen等。根据你要做的事情,也许你可以有一个设置变量的主Python实例,然后生成新的实例。

  2. You could run a shell script or batch file to set it for you, but that becomes much less portable. See this article:

    您可以运行shell脚本或批处理文件来为您设置它,但这样便可移植性降低。看到这篇文章:

http://code.activestate.com/recipes/159462/

#5


According to this discussion, you cannot do it. What are you trying to accomplish?

根据这个讨论,你不能这样做。你想达到什么目的?

#6


Think about it this way.

这样想吧。

You're not setting shell environment variables.

您没有设置shell环境变量。

You're spawning a subshell with some given environment variable settings; this subshell runs your application with the modified environment.

您正在使用某些给定的环境变量设置生成子shell;此子shell使用修改后的环境运行应用程序。

#7


You are forking a new process and cannot change the environment of the parent process as you cannot do if you start a new shell process from the shell

您正在分支新进程并且无法更改父进程的环境,因为如果从shell启动新的shell进程,则无法执行此操作

#8


You might want to try Python Win32 Extensions, developed by Mark Hammond, which is included in the ActivePython (or can be installed separately). You can learn how to perform many Windows related tasks in Hammond's and Robinson's book.

您可能想尝试由Mark Hammond开发的Python Win32 Extensions,它包含在ActivePython中(或者可以单独安装)。您可以在Hammond和Robinson的书中学习如何执行许多与Windows相关的任务。

Using PyWin32 to access windows COM objects, a Python program can use the Environment Property (a collection of environment variables) of the WScript.Shell object.

使用PyWin32访问Windows COM对象,Python程序可以使用WScript.Shell对象的Environment属性(环境变量的集合)。

#9


Seems like there is simplier solution for Windows

似乎有更简单的Windows解决方案

import subprocess 
subprocess.call(['setx', 'Hello', 'World!'], shell=True)

#10


From within Python? No, it can't be done!

从Python内部?不,它无法完成!

If you are not bound to Python, you should consider using shell scripts (sh, bash, etc). The "source" command allows you to run a script that modifies the environment and will "stick" like you want to the shell you "sourced" the script in. What's going on here is that the shell executes the script directly rather creating a sub-process to execute the script.

如果你没有绑定Python,你应该考虑使用shell脚本(sh,bash等)。 “source”命令允许你运行一个修改环境的脚本,并且会像你想要的那样“粘贴​​”你“源”脚本的shell。这里发生的是shell直接执行脚本而不是创建一个子-process来执行脚本。

This will be quite portable - you can use cygwin on windows to do this.

这将非常便携 - 您可以在Windows上使用cygwin来执行此操作。

#11


In case someone might need this info. I realize this was asked 7 yrs ago, but even I forget how sometimes. .

如果有人可能需要此信息。我意识到这是在7年前被问到的,但即使我有时也会忘记。 。

Yes there is a way to make them "stick" in windows. Simply go control panel, system, advanced system settings,when the system properties window opens you should see an option (button) for Environment Variables. .The process for getting to this is a little different depending on what OS you're using (google it).

是的,有一种方法可以让它们“坚持”在窗户中。只需转到控制面板,系统,高级系统设置,当系统属性窗口打开时,您应该看到环境变量的选项(按钮)。根据您正在使用的操作系统(google it),获取此功能的过程略有不同。

Choose that (click button), then the Environment Variables window will open. It has 2 split windows, the top one should be your "User Variables For yourusername". . .choose "new", then simply set the variable. For instance one of mine is "Database_Password = mypassword".

选择(单击按钮),然后将打开“环境变量”窗口。它有2个分割窗口,顶部窗口应该是您的“用户名变量”。 。 。选择“新”,然后简单地设置变量。例如,我的一个是“Database_Password = mypassword”。

Then in your app you can access them like this: import os, os.environ.get('Database_Password'). You can do something like pass = os.environ.get('Database_Password').

然后在您的应用程序中,您可以像这样访问它们:import os,os.environ.get('Database_Password')。您可以执行诸如pass = os.environ.get('Database_Password')之类的操作。

#1


Under Windows it's possible for you to make changes to environment variables persistent via the registry with this recipe, though it seems like overkill.

在Windows下,您可以使用此配方通过注册表对环境变量进行持久更改,尽管它看起来有点过分。

To echo Brian's question, what are you trying to accomplish? There is probably an easier way.

为了回应Brian的问题,你想要完成什么?可能有一种更简单的方法。

#2


make them stick by committing them to the system?

通过将它们提交给系统来使它们坚持下去?

I think you are a bit confused here. There is no 'system' environment. Each process has their own environment as part its memory. A process can only change its own environment. A process can set the initial environment for processes it creates.

我觉得你在这里有点困惑。没有“系统”环境。每个进程都有自己的环境作为其内存的一部分。流程只能改变自己的环境。进程可以为其创建的进程设置初始环境。

If you really do think you need to set environment variables for the system you will need to look at changing them in the location they get initially loaded from like the registry on windows or your shell configuration file on Linux.

如果您确实认为需要为系统设置环境变量,则需要在最初加载的位置更改它们,例如Windows上的注册表或Linux上的shell配置文件。

#3


You can using SETX at the command-line.

您可以在命令行中使用SETX。

By default these actions go on the USER env vars. To set and modify SYSTEM vars use the /M flag

默认情况下,这些操作会在USER env vars上进行。要设置和修改SYSTEM变量,请使用/ M标志

import os
env_var = "BUILD_NUMBER"
env_val = "3.1.3.3.7"
os.system("SETX {0} {1} /M".format(env_var,env_val))

#4


I don't believe you can do this; there are two work-arounds I can think of.

我不相信你能做到这一点;我能想到两种解决方法。

  1. The os.putenv function sets the environment for processes you start with, i.e. os.system, popen, etc. Depending on what you're trying to do, perhaps you could have one master Python instance that sets the variable, and then spawns new instances.

    os.putenv函数为你开始的进程设置环境,即os.system,popen等。根据你要做的事情,也许你可以有一个设置变量的主Python实例,然后生成新的实例。

  2. You could run a shell script or batch file to set it for you, but that becomes much less portable. See this article:

    您可以运行shell脚本或批处理文件来为您设置它,但这样便可移植性降低。看到这篇文章:

http://code.activestate.com/recipes/159462/

#5


According to this discussion, you cannot do it. What are you trying to accomplish?

根据这个讨论,你不能这样做。你想达到什么目的?

#6


Think about it this way.

这样想吧。

You're not setting shell environment variables.

您没有设置shell环境变量。

You're spawning a subshell with some given environment variable settings; this subshell runs your application with the modified environment.

您正在使用某些给定的环境变量设置生成子shell;此子shell使用修改后的环境运行应用程序。

#7


You are forking a new process and cannot change the environment of the parent process as you cannot do if you start a new shell process from the shell

您正在分支新进程并且无法更改父进程的环境,因为如果从shell启动新的shell进程,则无法执行此操作

#8


You might want to try Python Win32 Extensions, developed by Mark Hammond, which is included in the ActivePython (or can be installed separately). You can learn how to perform many Windows related tasks in Hammond's and Robinson's book.

您可能想尝试由Mark Hammond开发的Python Win32 Extensions,它包含在ActivePython中(或者可以单独安装)。您可以在Hammond和Robinson的书中学习如何执行许多与Windows相关的任务。

Using PyWin32 to access windows COM objects, a Python program can use the Environment Property (a collection of environment variables) of the WScript.Shell object.

使用PyWin32访问Windows COM对象,Python程序可以使用WScript.Shell对象的Environment属性(环境变量的集合)。

#9


Seems like there is simplier solution for Windows

似乎有更简单的Windows解决方案

import subprocess 
subprocess.call(['setx', 'Hello', 'World!'], shell=True)

#10


From within Python? No, it can't be done!

从Python内部?不,它无法完成!

If you are not bound to Python, you should consider using shell scripts (sh, bash, etc). The "source" command allows you to run a script that modifies the environment and will "stick" like you want to the shell you "sourced" the script in. What's going on here is that the shell executes the script directly rather creating a sub-process to execute the script.

如果你没有绑定Python,你应该考虑使用shell脚本(sh,bash等)。 “source”命令允许你运行一个修改环境的脚本,并且会像你想要的那样“粘贴​​”你“源”脚本的shell。这里发生的是shell直接执行脚本而不是创建一个子-process来执行脚本。

This will be quite portable - you can use cygwin on windows to do this.

这将非常便携 - 您可以在Windows上使用cygwin来执行此操作。

#11


In case someone might need this info. I realize this was asked 7 yrs ago, but even I forget how sometimes. .

如果有人可能需要此信息。我意识到这是在7年前被问到的,但即使我有时也会忘记。 。

Yes there is a way to make them "stick" in windows. Simply go control panel, system, advanced system settings,when the system properties window opens you should see an option (button) for Environment Variables. .The process for getting to this is a little different depending on what OS you're using (google it).

是的,有一种方法可以让它们“坚持”在窗户中。只需转到控制面板,系统,高级系统设置,当系统属性窗口打开时,您应该看到环境变量的选项(按钮)。根据您正在使用的操作系统(google it),获取此功能的过程略有不同。

Choose that (click button), then the Environment Variables window will open. It has 2 split windows, the top one should be your "User Variables For yourusername". . .choose "new", then simply set the variable. For instance one of mine is "Database_Password = mypassword".

选择(单击按钮),然后将打开“环境变量”窗口。它有2个分割窗口,顶部窗口应该是您的“用户名变量”。 。 。选择“新”,然后简单地设置变量。例如,我的一个是“Database_Password = mypassword”。

Then in your app you can access them like this: import os, os.environ.get('Database_Password'). You can do something like pass = os.environ.get('Database_Password').

然后在您的应用程序中,您可以像这样访问它们:import os,os.environ.get('Database_Password')。您可以执行诸如pass = os.environ.get('Database_Password')之类的操作。