如何在 Python 中进行环境变量更改? [英] How do I make environment variable changes stick in Python?

查看:39
本文介绍了如何在 Python 中进行环境变量更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的阅读,对 Python 实例中环境变量的任何更改仅在该实例中可用,并且在实例关闭后消失.有什么办法可以通过将它们提交到系统来让它们坚持下去?

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?

我需要这样做的原因是因为在我工作的工作室中,像 Maya 这样的工具严重依赖环境变量来配置跨多个平台的路径.

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.

我的测试代码是

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

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

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

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

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.

也就是说,我已经走上了使用 Windows 注册表技术的路线,并且将简单地编写替代方法,以便在需要时调用其他平台上的 shell 脚本.

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 下,您可以使用 这个食谱,虽然看起来有点矫枉过正.

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.

为了回应布赖恩的问题,您想要完成什么?可能有更简单的方法.

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

这篇关于如何在 Python 中进行环境变量更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆