What would be a pythonic way of resetting os.environ to the default values one would find in a command shell? I could handle this by first pushing os.environ into a default dictionary, but that method would fail in the event os.environ is changed by another module before mine is imported.
In Windows i'm currently able to reset values like so:
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)
My way works currently in python 2.7.3 64 bit, but i just noticed that when i run this in 32 bit, both the PROGRAMFILES and PROGRAMFILES(x86) env variables point to "Program Files (x86)" which is an issue discussed here.
Thanks in advance for all you help!