Loop through values or registry key.. _winreg Python

前端 未结 5 611
清歌不尽
清歌不尽 2021-01-17 21:40

How would I loop through all the values of a Windows Registry Key using the Python module _winreg. I have code that will do what I want, but it is

5条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-17 22:11

    I prefer to avoid the error instead of diving right into it ...

    Use _winreg.QueryInfoKey to get the number of values:

    import _winreg
    key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, r'PATH\TO\KEY', 0, _winreg.KEY_READ)
    
    for i in xrange(0, _winreg.QueryInfoKey(key)[1]):
        print _winreg.EnumValue(key, i)
    

    To get the number of Keys, same method, different index (second half of original question):

    for i in xrange(0, _winreg.QueryInfoKey(key)[0]):
        print _winreg.EnumKey(key, i)
    

    Note: use import instead of from ... import to make it explicit where functions and variables are coming from. Makes it easier to follow code later in life.

提交回复
热议问题