def setenv(self, name, value):
# Note: for 'system' scope, you must run this as Administrator
key = winreg.OpenKey(self.root, self.subkey, 0, winreg.KEY_ALL_ACCESS)
winreg.SetValueEx(key, name, 0, winreg.REG_EXPAND_SZ, value)
winreg.CloseKey(key)
# For some strange reason, calling SendMessage from the current process
# doesn't propagate environment changes at all.
# TODO: handle CalledProcessError (for assert)
check_call('''\
"%s" -c "import win32api, win32con; assert win32api.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment')"''' % sys.executable)
python类REG_EXPAND_SZ的实例源码
def sz_expand(value, value_type):
if value_type == reg.REG_EXPAND_SZ:
return reg.ExpandEnvironmentStrings(value)
else:
return value
def setEnvironment(scope, name, value):
assert scope in ('user', 'system')
#INFO_MSG('set environment: name=%s, value=%s' % (name, value))
if platform.system() == 'Windows':
root, subkey = getWindowsEnvironmentKey(scope)
# Note: for 'system' scope, you must run this as Administrator
key = winreg.OpenKey(root, subkey, 0, winreg.KEY_ALL_ACCESS)
winreg.SetValueEx(key, name, 0, winreg.REG_EXPAND_SZ, value)
winreg.CloseKey(key)
else:
if name.lower() == 'uid':
uid, username = value
if uid != str(os.geteuid()):
ret, cret = syscommand('bash -c \'usermod -d /home/%s/ -u %s %s\'' % (pwd.getpwnam(username).pw_dir, uid, username), True)
INFO_MSG(ret)
INFO_MSG(cret)
return
userhome = "~"
if len(os_user_name) > 0:
userhome = pwd.getpwnam(os_user_name).pw_dir
f = open('%s/.bashrc' % userhome, 'a')
f.write("export %s=%s\n\n" % (name, value))
f.close()
if os.geteuid() > 0:
syscommand('bash -c \'source %s/.bashrc\'' % userhome, False)