简体   繁体   English

在 Windows 上的 Python 中获取和设置环境变量

[英]Get and Set env vars in Python on Windows

I'm trying to set an env variable which I want it to be reachable from another windows shell (which is already opened):我正在尝试设置一个环境变量,我希望它可以从另一个 windows shell (已经打开)访问:

I have tried:我努力了:

os.environ['start'] = 'test'

Then in a Windows cmd: env.exe |然后在 Windows cmd: env.exe | findstr 'start' returns nothing. findstr 'start'什么都不返回。 Variable 'start' does not exist.变量“开始”不存在。

Then I tried:然后我尝试了:

subprocess.call(['setx.exe', 'start', 'test'])
SUCCESS: Specified value was saved

env.exe |环境.exe | findstr 'start' still returns nothing. findstr 'start'仍然不返回任何内容。

How can I get this variable from a windows shell?如何从 windows shell 中获取此变量? Using Windows 10 and python 3. Thanks!使用 Windows 10 和 python 3。谢谢!

You have to call the Windows SETX from your python code in order to make your environment value saved from your code您必须从您的 python 代码中调用 Windows SETX 才能从您的代码中保存您的环境值

os.system("SETX {0} {1} /M".format("start", "test"))

should do the trick.应该做的伎俩。 Dont forget to run your script as Administrator.不要忘记以管理员身份运行您的脚本。 In order for your command prompt to see the changes, make sure you close it and open a new command prompt, then try to find your environment value using env.exe为了让您的命令提示符看到更改,请确保关闭它并打开一个新的命令提示符,然后尝试使用 env.exe 查找您的环境值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM