def set_env_variables_permanently_win(key_value_pairs: Dict[str, Any], whole_machine: bool = False):
"""
Similar to os.environ[var_name] = var_value for all pairs provided, but instead of setting the variables in the
current process, sets the environment variables permanently at the os MACHINE level.
Recipe from http://code.activestate.com/recipes/416087/
:param key_value_pairs: a dictionary of variable name+value to set
:param whole_machine: if True the env variables will be set at the MACHINE (HKLM) level. If False it will be
done at USER level (HKCU)
:return:
"""
try:
path = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment' if whole_machine else r'Environment'
reg = ConnectRegistry(None, HKEY_LOCAL_MACHINE if whole_machine else HKEY_CURRENT_USER)
key = _open_key(reg, path, whole_machine)
if key_value_pairs is None:
# print all values..
show_win(key)
else:
for name, value in key_value_pairs.items():
if name.upper() == 'PATH':
# TODO maybe remove this security ?
warn('PATH can not be entirely changed. The value will be simply appended at the end.')
value = query_value_win(path, key, name, whole_machine) + ';' + value
if value:
print("Setting ENV VARIABLE '" + name + "' to '" + value + "'")
SetValueEx(key, name, 0, REG_EXPAND_SZ, value)
else:
print("Deleting ENV VARIABLE '" + name + "'")
try:
DeleteValue(key, name)
except FileNotFoundError:
# ignore if already deleted
pass
# this hangs forever, see https://stackoverflow.com/questions/1951658/sendmessagehwnd-broadcast-hangs
# win32gui.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment')
print("Broadcasting change to other windows")
win32gui.SendMessageTimeout(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment',
win32con.SMTO_ABORTIFHUNG, 1000)
finally:
# Always try to close everything in reverse order, silently
try:
CloseKey(key)
except:
pass
try:
CloseKey(reg)
except:
pass
评论列表
文章目录