Python's way of reading the values in the registry

  • 2020-04-02 13:11:05
  • OfStack

In Python's standard library, _winreg.pyd can operate the Windows registry, and the third-party win32 library encapsulates a large number of Windows apis, which is also very convenient to use. However, this is the use of _winreg operation registry, after all, is Python's own standard library, you do not need to install third-party libraries.

The following example is getting the installed patch number for Windows XP through Python. The patch number for Windows is under "HKEY_LOCAL_MACHINE\SOFTWARE\ Microsoft\ Updates", and it is a patch number if the name found matches the regular expression KB(\d{6}).

You can see from the example that it is very simple and fast to operate.


# -*- coding: utf-8 -*-
#  To obtain Windows Has been patched 

from _winreg import *
import re

def subRegKey(key, pattern, patchlist):
  #  The number of 
  count = QueryInfoKey(key)[0]
  for index in range(count):
    #  Get the title 
    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('(KBd{6}).*')
  key = OpenKey(HKEY_LOCAL_MACHINE, updates)
  subRegKey(key, patch, patchlist)
  print 'Count: ' + str(len(patchlist))
  for p in patchlist:
    print p
  CloseKey(key) 

The following is from   Python Standard Library12.13 The _winreg Module
(Windows only, The New 2.0) in The _winreg module provides a basic interface to The Windows registry database. The 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\WindowsCurrentVersion\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'
'Reason Setting' 'FaultCount' 'FaultTime' 'IconUnderline'...

user is u'Effbot'

That's all for this article


Related articles: