在Python的標準庫中,_winreg.pyd可以操作Windows的註冊表,另外第三方的win32庫封裝了大量的Windows API,使用起來也很方便。不過這裡介紹的是使用_winreg操作註冊表,畢竟是Python內建的標準庫,無需安裝第三方庫。
下面的例子是通過Python擷取Windows XP下已經安裝的補丁號。Windows的補丁號都在“HKEY_LOCAL_MACHINE\SOFTWARE\\Microsoft\\Updates”下,通過迴圈下面所有的目錄節點,如果找到的名稱符合RegexKB(\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'