首页 > 解决方案 > Python - 当真:尝试除其他 - 程序流问题

问题描述

我有这个代码使用 aWhile True和 a try catch。当“尝试”成功时,总是会执行最后的 else 语句,我想了解原因 - 我认为我没有正确理解程序流程。

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

标签: pythonwhile-looptry-except

解决方案


基于python 文档,try-except 可以采用可选的 else 语句:

try ... except 语句有一个可选的 else 子句,当它出现时,它必须跟在所有 except 子句之后。如果 try 子句不引发异常,则它对于必须执行的代码很有用。

因此,基于此,如果 try 中的代码没有引发任何异常,则 else 语句将运行!

您想要的是另一个捕获一般异常的 except 子句,因此您只需替换elseexcept

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
    except:
        print("something else went wrong while trying to download splunk")
        break



推荐阅读