将 os.environ 重置为在命令 shell 中可以找到的默认值的 pythonic 方式是什么?我可以通过首先将 os.environ 推送到默认字典中来处理这个问题,但是如果 os.environ 在导入我的模块之前被另一个模块更改,该方法将失败。
在 Windows 中,我目前可以像这样重置值:
import os, subprocess, tempfile
def is_locked(filepath):
''' Needed to determine when the set command below completes
'''
locked = None
file_object = None
if os.path.exists(filepath):
try:
buffer_size = 8
file_object = open(filepath, 'a', buffer_size)
if file_object:
locked = False
except IOError, message:
locked = True
finally:
if file_object:
file_object.close()
else:
locked = True
return locked
# Define a Windows command which would dump default env variables into a tempfile
#
# - start /i will give default cmd.exe environment variable to what follows.
# It's the only way i found to get cmd.exe's default env variables and because
# start terminates immediately i need to use is_locked defined above to wait for
# Window's set command to finish dumping it's variables into the temp file
# - /b is will prevent a command shell to pop up
temp = tempfile.mktemp()
cmd = 'start /i /b cmd /c set>%s'%temp
p = subprocess.Popen(cmd, shell=True)
p.wait()
# Wait for the command to complete and parse the tempfile
data = []
while(is_locked(temp)):
pass
with open(temp,'r') as file:
data = file.readlines()
os.remove(temp)
# defaults will contain default env variables
defaults = dict()
for env in data:
env = env.strip().split('=')
defaults[env[0]]=env[1]
print '%s %s'%(env[0],env[1])
os.environ = dict(defaults)
我的方式目前在 python 2.7.3 64 位中有效,但我只是注意到当我在 32 位中运行它时,PROGRAMFILES 和 PROGRAMFILES(x86) env 变量都指向“程序文件 (x86)”,这是这里讨论的一个问题.
在此先感谢您的帮助!