我想观看某个注册表项的更改,并在使用Python更改后立即执行一些自动操作,例如,程序在启动过程中更改了注册表项,而我想在此后立即将其强制为旧值。
以下示例代码将强制计算器以日期时间模板开头,而不考虑最后使用的模板。它使用Python for Windows扩展,提供了一种真正快速的方法来访问大多数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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句