Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through values or registry key.. _winreg Python

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 for the subkeys of the specified registry key.


Here Is The Code:

from _winreg import *
t = OpenKey(HKEY_CURRENT_USER, r"PATH TO KEY", 0, KEY_ALL_ACCESS)

try:
    i = 0
    while True:
        subkey = EnumValue(t, i)
        print subkey
        i += 1
except WindowsError:
    # WindowsError: [Errno 259] No more data is available    
    pass

Oh, figured it out. But, if anyone knows of another way to do it, I'll still accept that answer!

like image 892
Zac Brown Avatar asked Oct 20 '10 01:10

Zac Brown


3 Answers

Shouldn't EnumValue be of help here

# list all values for a key
try:
    count = 0
    while 1:
        name, value, type = _winreg.EnumValue(t, count)
        print repr(name),
        count = count + 1
except WindowsError:
    pass
like image 77
pyfunc Avatar answered Nov 01 '22 06:11

pyfunc


for python 3

import winreg
hKey = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, "Local Settings\\Software\\Microsoft\\Windows\\Shell\\MuiCache")


try:
    count = 0
    while 1:
        name, value, type = winreg.EnumValue(hKey, count)
        print (name),
        count = count + 1
except WindowsError as err:
    print(err)
    pass
like image 31
Anagnostou John Avatar answered Nov 01 '22 06:11

Anagnostou John


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.

like image 38
VertigoRay Avatar answered Nov 01 '22 06:11

VertigoRay