在python的标准库中,_winreg.pyd可以操作windows的注册表,另外第三方的win32库封装了大量的windows api,使用起来也很方便。不过这里介绍的是使用_winreg操作注册表,毕竟是python自带的标准库,无需安装第三方库。

下面的例子是通过python获取windows xp下已经安装的补丁号。windows的补丁号都在“hkey_local_machine\software\\microsoft\\updates”下,通过循环下面所有的目录节点,如果找到的名称符合正则表达式kb(\d{6}).*,则表示是一个补丁号。

从例子可以看出操作起来非常的简单和快速。

# -*- coding: utf-8 -*-
# 获取windows的已打的补丁号
from _winreg import *
import re
def subregkey(key, pattern, patchlist):
# 个数
count = queryinfokey(key)[0]
for index in range(count):
# 获取标题
name = enumkey(key, index)
result = patch.match(name)
if result:
patchlist.append(result.group(1))
sub = openkey(key, name)
subregkey(sub, pattern, patchlist)
closekey(sub)
if __name__ == '__main__':
patchlist = []
updates = 'software\\microsoft\\updates'
patch = re.compile('(kb\d{6}).*')
key = openkey(hkey_local_machine, updates)
subregkey(key, patch, patchlist)
print 'count: ' + str(len(patchlist))
for p in patchlist:
print p
closekey(key)
下面内容转自  python standard library12.13 the _winreg module
(windows only, new in 2.0) the _winreg module provides a basic interface to the windows registry database. example 12-17 demonstrates the module.
example 12-17. using the _winreg module
file: winreg-example-1.py
import _winreg
explorer = _winreg.openkey(
_winreg.hkey_current_user,
"software\\microsoft\\windows\currentversion\\explorer"
)
#list values owned by this registry key
try:
i = 0
while 1:
name, value, type= _winreg.enumvalue(explorer, i)
print repr(name),
i += 1
except windowserror:
print
value, type = _winreg.queryvalueex(explorer, "logon user name")
print
print "user is", repr(value)
'logon user name' 'cleanshutdown' 'shellstate' 'shutdown setting'
'reason setting' 'faultcount' 'faulttime' 'iconunderline'...
user is u'effbot'

如您对本文有疑问或者有任何想说的,请点击进行留言回复