Python之注冊表增刪改查(干貨)


在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'SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto 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!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM