我希望观看某个注册表项以进行更改,并在Python更改后立即执行一些自动操作,例如:程序在启动期间更改注册表项,我想在之后强制键到旧值。
答案 0 :(得分:4)
以下示例代码将强制计算器以日期时间模板开始,而不管上次使用的模板如何。它使用Python for Windows extensions,它提供了一种非常快速的方式来访问大多数Windows内部并自动化COM感知应用程序:
import win32api
import win32con
import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s', filename='watchRegistry.log')
log = logging.getLogger()
hiveToWatch = win32con.HKEY_CURRENT_USER
keyToWatch = r'Software\Microsoft\Calc'
values = {(hiveToWatch, keyToWatch, 'DateTime'): (win32con.REG_DWORD, 1),
(hiveToWatch, keyToWatch, 'Templates'): (win32con.REG_DWORD, 0),
(hiveToWatch, keyToWatch, 'UnitConv'): (win32con.REG_DWORD, 0)}
while True:
for (hive, key, valueName), (valueType, value) in values.items():
handleWithSetRights = win32api.RegOpenKeyEx(hive, key, 0, win32con.KEY_SET_VALUE)
log.info(r'Setting %s\%s\%s = %s' % (hive, key, valueName, value))
win32api.RegSetValueEx(handleWithSetRights, valueName, 0, valueType, value)
win32api.RegCloseKey(handleWithSetRights)
# Open and close the handle here as otherwise the set operation above will trigger a further round
handleToBeWatched = win32api.RegOpenKeyEx(hiveToWatch, keyToWatch, 0, win32con.KEY_NOTIFY)
win32api.RegNotifyChangeKeyValue(handleToBeWatched, False, win32api.REG_NOTIFY_CHANGE_LAST_SET, None, False)
win32api.RegCloseKey(handleToBeWatched)