Skip to content

Instantly share code, notes, and snippets.

@socrateslee
Created May 28, 2013 13:44
Show Gist options
  • Save socrateslee/5662854 to your computer and use it in GitHub Desktop.
Save socrateslee/5662854 to your computer and use it in GitHub Desktop.
A simple command line tool for managing windows PATH variable in Windows Registry. Get help by `python winpath.py help`.
'''
A simple command line tool for managing windows PATH variable.
'''
import _winreg as winreg
import os
import sys
def choose_key(scope, write=False):
'''
Choose the winreg key.
'''
param = []
if scope == 'user':
param = [winreg.HKEY_CURRENT_USER,
"Environment"]
elif scope == 'system':
param = [winreg.HKEY_LOCAL_MACHINE,
"SYSTEM\CurrentControlSet\Control\Session Manager\Environment"]
else:
raise Exception('Unknown scope %s.' % scope)
if write:
param.extend([0, winreg.KEY_ALL_ACCESS])
return winreg.OpenKey(*param)
def get_path(scope):
'''
Get the PATH variable content w.r.t. the scope.
'''
key = choose_key(scope)
path = winreg.QueryValueEx(key, 'path')[0]
return path.strip()
def display_path(path):
'''
Split the PATH variable by ; and output.
'''
for i in path.split(';'):
print i
class PathOp(object):
@classmethod
def list(cls, scope=None):
'''
list [scope]
scope could be user or system, which will list
the paths from current user or system variables.
If scope is omitted, both user and system paths
will be listed.
'''
scope = ['user', 'system'] if scope is None else [scope]
for s in scope:
display_path(get_path(s))
@classmethod
def find(cls, target_path):
'''
find target_path
Find the target_path in user/system paths.
'''
for scope in ['user', 'system']:
path = get_path(scope)
if target_path.lower() in path.lower():
print "Find %s in %s path" % (target_path, scope)
@classmethod
def add(cls, scope, target_path):
'''
add scope target_path
Add target_path in specfied scope.
The scope could be user or system
'''
current_path = get_path(scope)
if target_path.lower() in current_path.lower():
print "%s is already in the PATH." % target_path
return
key = choose_key(scope, write=True)
current_path = (current_path + ';') if not current_path.endswith(';') else current_path
new_path = current_path + target_path
winreg.SetValueEx(key, "path", 0, winreg.REG_EXPAND_SZ, new_path)
print "Add %s in %s path." % (target_path, scope)
@classmethod
def remove(cls, target_path):
'''
remove target_path
Remove the target_path from user/system paths.
'''
for scope in ['user', 'system']:
path = get_path(scope)
if target_path.lower() in path.lower():
index = path.lower().find(target_path.lower())
new_path = path[:index] + path[index+len(target_path):]
new_path = new_path.replace(';;', ';')
key = choose_key(scope, write=True)
winreg.SetValueEx(key, "path", 0, winreg.REG_EXPAND_SZ, new_path)
print 'Remove %s in %s path.' % (target_path, scope)
@classmethod
def help(cls, command=None):
if command is None:
print "winpath.py is a simple tool to manage your PATH"
print "Usage:"
print "python winpath.py cmd [options]"
print "cmd may be list, find, add, remove"
print "Use"
print "python winpath.py help cmd"
print "to get detail help of a command."
print "If you gonna change system paths, Administrator permission is required."
else:
if command in ('list', 'find', 'add', 'remove'):
print getattr(cls, command).__doc__
def main():
if len(sys.argv)<2:
PathOp.help()
sys.exit(0)
cmd = sys.argv[1]
if hasattr(PathOp, cmd):
getattr(PathOp, cmd)(*sys.argv[2:])
if __name__ == '__main__':
main()
@monti-python
Copy link

Great tool @socrateslee, exactly what I was looking for. Thanks a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment