一、基本操作
python中的_winreg
模块提供了对于windows
平台下注册表的一些基本操作,包括对键值的枚举以及增加删除键等,以HKEY_CURRENT_USERConsole
为例:
OpenKey(key, subKey)
:打开一个键,第一个参数是常量,例如reg.HEKY_CURRENT_USER
,已经被系统定义好。CloseKey(key)
:关闭打开的键。EnumKey(key, index)
:枚举所有的key
。EnumValue(key, index)
:枚举所有的value
,有三个返回值:键值名
,键值
,键类型
。
例如,枚举上面注册表所有的键值:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# -*- coding:utf8 -*- import _winreg as reg def test(): key = reg.OpenKey(reg.HKEY_CURRENT_USER, "Console") try: print "-----get subKeys-----" i = 0 while True: #一直枚举,枚举完毕之后会抛出错误ERROR 259 name = reg.EnumKey(key, i) i += 1 print name except Exception as e: print e try: print "-----get subValues-----" i = 0 while True: k, v, t = reg.EnumValue(key, i) i += 1 print k, v, t except Exception as e: print e reg.CloseKey(key) if __name__ == "__main__": test() |
输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
-----get subKeys----- %SystemRoot%_System32_WindowsPowerShell_v1.0_powershell.exe %SystemRoot%_SysWOW64_WindowsPowerShell_v1.0_powershell.exe Git Bash Git CMD [Error 259] ## 枚举到最后会抛出错误Error 259 -----get subValues----- ColorTable00 0 4 ColorTable01 8388608 4 ColorTable02 32768 4 ColorTable03 8421376 4 ColorTable04 128 4 ColorTable05 8388736 4 ColorTable06 32896 4 ColorTable07 12632256 4 ColorTable08 8421504 4 ColorTable09 16711680 4 ColorTable10 65280 4 ColorTable11 16776960 4 ColorTable12 255 4 ColorTable13 16711935 4 ColorTable14 65535 4 ColorTable15 16777215 4 CtrlKeyShortcutsDisabled 0 4 CursorSize 25 4 EnableColorSelection 0 4 ExtendedEditKey 1 4 ExtendedEditKeyCustom 0 4 FaceName __DefaultTTFont__ 1 FilterOnPaste 1 4 FontFamily 0 4 FontSize 1048576 4 FontWeight 0 4 ForceV2 1 4 FullScreen 0 4 HistoryBufferSize 50 4 HistoryNoDup 0 4 InsertMode 1 4 LineSelection 1 4 LineWrap 1 4 LoadConIme 1 4 NumberOfHistoryBuffers 4 4 PopupColors 245 4 QuickEdit 1 4 ScreenBufferSize 589889656 4 ScreenColors 7 4 ScrollScale 1 4 TrimLeadingZeros 0 4 WindowAlpha 255 4 WindowSize 1966200 4 WordDelimiters 0 4 [Error 259] |
二、增加和删除键值
CreateKey(key, sub_key)
:创建一个新键,如果键存在就不会创建。SetValueEx(key, value_name, reserved, type, value)
:给一个键值赋值,如果键不存在将会自动创建。SetValue(key, sub_key, type, value)
:设置一个子键,并给予一个默认值value
。DeleteKey(key, sub_key)
:删除键
示例:
1 2 3 4 5 6 7 |
key = reg.OpenKey(reg.HKEY_CURRENT_USER, "Console") try: newKey = reg.CreateKey(key, r"test") # 创建一个子键 reg.SetValueEx(newKey, r"newKey", 0, reg.REG_SZ, "HelloWorld") reg.SetValue(newKey, r"newSubKey", reg.REG_SZ, "Hey") except Exception as e: print e |
运行后的结果:
三、问题
3.1 WindwosError: Error 5
没有权限导致的,OpenKey
中的sam
变量表明了操作的权限,默认是KEY_READ
,改成KEY_ALL_ACCESS
然后以管理员身份运行即可。例如:
1 2 |
KEY = r"SYSTEMControlSet001ControlClass{4d36e968-e325-11ce-bfc1-08002be10318}" key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, KEY, 0, _winreg.KEY_ALL_ACCESS) |
评论