Search code examples
pythonwhile-looptry-except

Python - While True: Try Except Else - Program Flow Question


I have this code using a While True with a try catch. The final else statement is always being executed when the 'try' is successful and I'd like to understand why - I think I'm not understanding the program flow correctly.

while True:
    try:
        subprocess.call(["wget", "-O", "splunk-8.0.1-6db836e2fb9e-Linux-x86_64.tgz", "https://www.splunk.com/bin/splunk/DownloadActivityServlet?architecture=x86_64&platform=linux&version=8.0.1&product=splunk&filename=splunk-8.0.1-6db836e2fb9e-Linux-x86_64.tgz&wget=true"])
        print("successfully downloaded splunk enterprise")
        time.sleep(2)
    except OSError as e:
        if e.errno == 2:
            print(e)
            print("wget doesn't seem to be installed")
            time.sleep(2)
            print("attempting to install wget")
            time.sleep(2)
            subprocess.call(["yum", "install", "wget"])
        else:
            print(e)
            print("unknown error response, exiting...")
            break
    else:
        print("something else went wrong while trying to download splunk")
        break

Solution

  • The else clause of a try executes if the code inside the try did not throw an exception. If you want to catch any exception, use except without specifying an exception class:

    except:
        print("something else went wrong while trying to download splunk")
        break
    

    However, consider just omitting this piece of code. As it is currently written, it doesn't tell you what went wrong. If you remove these lines, you will get an error message that tells you what happened and on which line the error occurred.