_winreg.EnumKey(key, i) does not workng?
Question: Hy, I trying to reconstruate a script. And in python 3 I used _winreg and the
script was working, but I need it in python 2 and now I get this erorr:

    
    
    File "discoverNetworks.py", line 14, in printNets
    guid = _winreg.EnumKey(key, i)
    WindowsError: [Error 259] No more data is available
    

But of course in that folder is a lot of files.

This is the code:

    
    
    import _winreg
    def val2addr(val):
        addr = ''
        for ch in val:
            addr += '%02x '% ord(ch)
        addr = addr.strip(' ').replace(' ', ':')[0:17]
        return addr
    def printNets():
        net = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkList\\Signatures\\Unmanaged"
        key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,net)
        print '\n[*] Networks You have Joined.'
        for i in range(100):
            try:
                guid = _winreg.EnumKey(key, i)
                netKey = _winreg.OpenKey(key, str(guid))
                (n, addr, t) = _winreg.EnumValue(netKey, 5)
                (n, name, t) = EnumValue(netKey, 4)
                macAddr = val2addr(addr)
                netName = str(name)
                print '[+] ' + netName + ' ' + macAddr
                _winreg.CloseKey(guid)
            except WindowsError:
                break
    def main():
        printNets()
    if __name__ == "__main__":
        main()
    

* * *

Thanks!


Answer: `EnumKey()` is designed to be called repeatedly until a `WindowsError` is
thrown. From [the
documentation](https://docs.python.org/2/library/_winreg.html#_winreg.EnumKey):

> winreg.**EnumKey**(_key, index_)
>
> . . .
>
> The function retrieves the name of one subkey each time it is called. It is
> typically called repeatedly until a `WindowsError` exception is raised,
> indicating, no more values are available.

However, the reason you did not receive a `WindowsError` when you ran it in
Python 3 is because [the library changed in Python 3.3 to throw an `OSError`
instead.](https://docs.python.org/3.4/library/winreg.html?highlight=_winreg#exception-
changed)

In fact, `EnvironmentError`, `IOError`, `WindowsError`, `VMSError`,
`socket.error`, `select.error` and `mmap.error` have been merged into
`OSError` in 3.3
([source](https://docs.python.org/3.4/library/exceptions.html#OSError)).

You can handle the error via exception handling (`except WindowsError`) or
avoid it altogether by determining the number of values ahead of time with
[`QueryInfoKey`](http://docs.python.org/2/library/_winreg.html#_winreg.QueryInfoKey)
as demonstrated in [this answer](http://stackoverflow.com/a/17563506/).

