在Windows平台下,对注册表的增删改查的需求比较多,微软提供了很多用于访问,修改注册表等的API,我们可以使用诸如bat,或者C++等各种方式去访问修改注册表。无所不能的python下如何完成这些操作呢?pywin32模块中提供了与微软提供的C++等语言API一致的使用python对注册表进行操作的接口。今天带给大家的是对注册表进行修改的代码(PS:想使用的孩纸直接复制拿走,亲测可用!)需要的孩纸们直接看代码:
1 import win32api, win32con 2 import sys 3 4 __author__ = 'Berlin' 5 6 def ModifyReg(key, keyPath, valueName, valueType, value): 7 try: 8 ''' 9 RegConnectRegistry: 10 computerName: string(If None, the local computer is used) 11 key: int(May be win32con.HKEY_LOCAL_MACHINE...) 12 ''' 13 keyHandle = win32api.RegConnectRegistry(None, key) 14 ''' 15 RegOpenKeyEx: 16 key: PyHKEY/int 17 subKey: string 18 reserved = 0: int(Reserved. Must be zero.) 19 sam = KEY_READ: int(If you want to set the value later, you must open the key with KEY_SET_VALUE) 20 ''' 21 subkeyHandle = win32api.RegOpenKeyEx(keyHandle, keyPath) 22 ''' 23 RegQueryValueEx: 24 key: PyHKEY/int 25 valueName: The name of the value to query 26 ''' 27 (currValue, type) = win32api.RegQueryValueEx(subkeyHandle, valueName) 28 if (currValue == value): 29 print 'PASS: Check reg value: %s' % valueName 30 return 1 31 else: 32 print 'INFO: The %s is not the same as %s' % (valueName, value) 33 print 'INFO: Try to set %s as %s' %(valueName, value) 34 subkeyHandle = win32api.RegOpenKeyEx(keyHandle, keyPath, 0, win32con.KEY_SET_VALUE) 35 ''' 36 RegSetValueEx: 37 key: PyHKEY/int 38 valueName: string(The name of the value to set) 39 reserved: any(Zero will always be passed to the API function) 40 type: int(REG_DWORD, REG_SZ ...) 41 value: registry data 42 ''' 43 win32api.RegSetValueEx(subkeyHandle, valueName, 0, valueType, value) 44 except: 45 print 'FAIL: ModifyReg %s. Exception happened. Exception happened when accessing registry key under %s.' % (valueName, keyPath) 46 return 0 47 print 'SUCCESS: ModifyReg %s value under %s' % (valueName, keyPath) 48 return 1 49 50 def main(): 51 key = win32con.HKEY_LOCAL_MACHINE 52 AUPath = r'SOFTWAREMicrosoftWindowsCurrentVersionWindowsUpdateAuto Update' 53 valueName = r'AUOptions' 54 valueType = win32con.REG_DWORD 55 value = 1 56 ModifyReg(key, AUPath, valueName, valueType, value) 57 58 if __name__ == '__main__': 59 sys.exit(main())
实例是修改Windows自动更新的注册表项,将其修改为1.
感谢阅读,希望能帮到大家!
Published by Windows Live Writer!