使用Python添加环境变量 [英] Add an environment variable using Python

查看:237
本文介绍了使用Python添加环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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添加环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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