python2.7版本
# coding=utf8 import os import sys from subprocess import check_call if sys.hexversion > 0x03000000: import winreg else: import _winreg as winreg class Win32Environment: """Utility class to get/set windows environment variable""" def __init__(self, scope): # assert scope in ('user', 'system') self.scope = scope if scope == 'user': self.root = winreg.HKEY_CURRENT_USER self.subkey = 'Environment' else: self.root = winreg.HKEY_LOCAL_MACHINE self.subkey = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment' def getenv(self, name): key = winreg.OpenKey(self.root, self.subkey, 0, winreg.KEY_READ) try: value, _ = winreg.QueryValueEx(key, name) except WindowsError: value = '' return value def setValue(self, name, value,type=winreg.REG_EXPAND_SZ): # 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, type, value) winreg.CloseKey(key) # 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) def get_userenv(self, name): # Note: for 'system' scope, you must run this as Administrator key = winreg.OpenKey(self.root, self.subkey, 0, winreg.KEY_ALL_ACCESS) value, _ = winreg.QueryValueEx(key, name) return value def deleteKey(self,name): key = winreg.OpenKey(self.root, self.subkey, 0, winreg.KEY_ALL_ACCESS) value, _ = winreg.DeleteKey(key, name) return value def get_value(name): e2 = Win32Environment(scope="user") res =e2.get_userenv(name) return '注册表查询完成,{}的值为{}'.format(name,res) def set_value(name,value,input_type=None): if input_type=='string': input_type=winreg.REG_SZ elif input_type=='binary': input_type = winreg.REG_BINARY elif input_type=='dword': input_type=winreg.REG_DWORD else: input_type=winreg.REG_EXPAND_SZ e2 = Win32Environment(scope="user") e2.setValue(name,value,type=input_type) return '注册表设置完成' def del_key(name): try: e2 = Win32Environment(scope="user") e2.deleteKey(name) return '注册表删除完成' except Exception as e: print e print '删除失败,请查看父节点是否设置成完全控制,详情查看WOW6432Node配置' sys.exit(1) if __name__ == '__main__': if func=='get': print get_value(name) elif func=='set': print set_value(name,value,input_type=input_type) elif func=='del': print del_key(name) else: print '请在func参数中填入get,set或del' sys.exit(1)