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)
python类SetValueEx()的实例源码
def jit(vdb, line):
'''
Enable/Disable the current VDB location as the current Just-In-Time
debugger for windows applications.
Usage: jitenable [-D]
-E Enable VDB JIT debugging
-D Disable JIT debugging
'''
argv = e_cli.splitargs(line)
try:
opts, args = getopt.getopt(argv, "ED")
except Exception as e:
return vdb.do_help('jit')
try:
import winreg
except Exception as e:
vdb.vprint('Error Importing _winreg: %s' % e)
return
HKLM = winreg.HKEY_LOCAL_MACHINE
HKCU = winreg.HKEY_CURRENT_USER
REG_SZ = winreg.REG_SZ
regpath = r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug'
# wow64path = r'SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\AeDebug'
# regkey = _winreg.CreateKey(HKLM, regpath)
regkey = winreg.CreateKey(HKLM, regpath)
vdb.vprint('JIT Currently: %s' % winreg.QueryValueEx(regkey, 'Debugger')[0])
setval = None
for opt, optarg in opts:
if opt == '-D':
setval = ''
elif opt == '-E':
vdbpath = os.path.abspath(sys.argv[0])
setval = '%s %s -r -p %%ld -e %%Id' % (sys.executable, vdbpath)
# _winreg.SetValue(HKLM
if setval != None:
vdb.vprint('Setting JIT: %s' % (setval,))
winreg.SetValueEx(regkey, 'Debugger', None, REG_SZ, setval)