问题描述
import os
os.environ [TONY] =C:\\
或
import os
os.putenv [TONY,C:\\]
但我没有看到系统环境变量中的条目。是因为在cmd中键入set的变量列表是从机器注册表中读取的?
有没有办法在Windows上添加变量,以便显示在系统变量中?
简短的回答:Python不能以一种方式编辑环境变量。但是,如果你想做的只是在临时修改的环境中运行某些东西,你可以使用子进程模块:
从子进程导入os
Popen
myEnv = dict(os.environ)
myEnv ['newKey'] ='newVal'
shellCmd = Popen([' sh','someScript.sh'],env = myEnv)
(shellOut,shellErr)= shellCmd.communicate()
I'm trying to add an environment variable to my windows machine using python and the code is something like:
import os
os.environ["TONY"] = "C:\\"
or
import os
os.putenv["TONY", "C:\\"]
But I dont see the entry in the system environment variables. Is the because the list of variables when you type 'set' in cmd is read from the machines registry?
Is there a way to add a variable on windows so it shows up in system variables?
Short answer: Python cannot edit environment variables in a way that sticks. BUT, if all you want to do is run something in a temporarily modified environment, you can do that with the subprocess module:
import os
from subprocess import Popen
myEnv = dict(os.environ)
myEnv['newKey'] = 'newVal'
shellCmd = Popen(['sh', 'someScript.sh'], env=myEnv)
(shellOut, shellErr) = shellCmd.communicate()
这篇关于使用Python添加环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!