Python Forum

Full Version: Loop Condition Question
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to iterate over a loop until an OSError is thrown. That's it. What's the best way to do that. What I'm doing is using winreg.EnumKey to make a list of all sub-keys of a key. The function returns one key at a time. So, I need to loop it, increasing the index each time to enum all keys. How do I stop the loop at an OSError (which is what the docs recommend)?
Just to show some code (this is not how I want to do it)
i = 0
while i < 5:
    list = winreg.EnumKey(<key>, i)
    i += 1
I want something like
while not OSError:
    ....
But my limited understanding is causing errors.

Help is, as always, much appreciated.
malonn
I am assuming you have tried:

i = 0
while not OSError:
  list = winreg.EnumKey(<key>, i)
  i += 1
what error did you get?
I'm not sure the error, but it throws one at the while condition in the following code:
reg_key = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkList\\Profiles'

if ctypes.windll.shell32.IsUserAnAdmin():
    with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, reg_key, 0, winreg.KEY_ALL_ACCESS) as k:
        ns = winreg.QueryInfoKey(k)[0]
        if ns > 1:
            i = 0
            while not OSError:
                subs = winreg.EnumKey(k, i)
                i += 1
            print(subs)
    input('Check your Regedit.')
else:
    ctypes.windll.shell32.ShellExecuteW(None, 'runas', sys.executable, 'run_as.py', None, 1)
I checked by placing an input() call right after
while not OSError:
line and the screen does not pause for user input. So, it errors out at that line, I just can't figure out how to trap the error.
If you are expecting the OSError from the winreg call:

i = 0
while i < 5:
    try:
        list = winreg.EnumKey(<key>, i)
    except OSError:
        break
    i += 1
Although, that's really a for loop:

for i in range(5):
    try:
        list = winreg.EnumKey(<key>, i)
    except OSError:
        break
Hey, thanks @Vysero and @ichabod801! I was thinking I may need a try:except: thingy (still learning), but wasn't sure. It works great though @ichabod801; thanks.

Problem solved.
I did not realize you were trying to throw the error. I thought you were trying to loop off of the catch.
Yeah, NP. The function errors when there is no more sub-keys within a key.

Time to post my next sticking point in a new thread...