def remove_from_system_path(pathname, allusers=True, path_env_var='PATH'):
"""Removes all entries from the path which match the value in 'pathname'
You must call broadcast_environment_settings_change() after you are finished
manipulating the environment with this and other functions.
For example,
# Remove Anaconda from PATH
remove_from_system_path(r'C:\Anaconda')
broadcast_environment_settings_change()
"""
pathname = path.normcase(path.normpath(pathname))
envkeys = [(reg.HKEY_CURRENT_USER, r'Environment')]
if allusers:
envkeys.append((reg.HKEY_LOCAL_MACHINE,
r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'))
for root, keyname in envkeys:
key = reg.OpenKey(root, keyname, 0,
reg.KEY_QUERY_VALUE|reg.KEY_SET_VALUE)
reg_value = None
try:
reg_value = reg.QueryValueEx(key, path_env_var)
except WindowsError:
# This will happen if we're a non-admin install and the user has
# no PATH variable.
reg.CloseKey(key)
continue
try:
any_change = False
results = []
for v in reg_value[0].split(os.pathsep):
vexp = sz_expand(v, reg_value[1])
# Check if the expanded path matches the
# requested path in a normalized way
if path.normcase(path.normpath(vexp)) == pathname:
any_change = True
else:
# Append the original unexpanded version to the results
results.append(v)
modified_path = os.pathsep.join(results)
if any_change:
reg.SetValueEx(key, path_env_var, 0, reg_value[1], modified_path)
except:
# If there's an error (e.g. when there is no PATH for the current
# user), continue on to try the next root/keyname pair
reg.CloseKey(key)
评论列表
文章目录