在Python的標(biāo)準(zhǔn)庫中,_winreg.pyd可以操作Windows的注冊(cè)表,另外第三方的win32庫封裝了大量的Windows API,使用起來也很方便。不過這里介紹的是使用_winreg操作注冊(cè)表,畢竟是Python自帶的標(biāo)準(zhǔn)庫,無需安裝第三方庫。
下面的例子是通過Python獲取Windows XP下已經(jīng)安裝的補(bǔ)丁號(hào)。Windows的補(bǔ)丁號(hào)都在“HKEY_LOCAL_MACHINE/SOFTWARE//Microsoft//Updates”下,通過循環(huán)下面所有的目錄節(jié)點(diǎn),如果找到的名稱符合正則表達(dá)式KB(/d{6}).*,則表示是一個(gè)補(bǔ)丁號(hào)。
從例子可以看出操作起來非常的簡(jiǎn)單和快速。
代碼如下:
# -*- coding: utf-8 -*-
# 獲取Windows的已打的補(bǔ)丁號(hào)
from _winreg import *
import re
def subRegKey(key, pattern, patchlist):
# 個(gè)數(shù)
count = QueryInfoKey(key)[0]
for index in range(count):
# 獲取標(biāo)題
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)
下面內(nèi)容轉(zhuǎn)自 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'
新聞熱點(diǎn)
疑難解答
圖片精選