Python Forum
Loop Condition Question - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Loop Condition Question (/thread-11912.html)



Loop Condition Question - malonn - Jul-31-2018

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


RE: Loop Condition Question - Vysero - Jul-31-2018

I am assuming you have tried:

i = 0
while not OSError:
  list = winreg.EnumKey(<key>, i)
  i += 1
what error did you get?


RE: Loop Condition Question - malonn - Jul-31-2018

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.


RE: Loop Condition Question - ichabod801 - Jul-31-2018

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



RE: Loop Condition Question - malonn - Jul-31-2018

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.


RE: Loop Condition Question - Vysero - Jul-31-2018

I did not realize you were trying to throw the error. I thought you were trying to loop off of the catch.


RE: Loop Condition Question - malonn - Aug-01-2018

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...