Python - 虽然为真 : Try Except Else - Program Flow Question

标签 python while-loop try-except

我的代码使用了 While Truetry catch。当“try”成功时,最后的 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

最佳答案

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

The try … except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception.

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

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

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


关于Python - 虽然为真 : Try Except Else - Program Flow Question,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59861855/

相关文章:

python - 我正在使用 py2neo 将 python 连接到 neo4j 数据库

c++ - 从 for 循环到另一个循环的变量

python - PYTHON 中的 for 循环 while 循环效率

python - 如何正确忽略异常

python - 模拟子对象中的返回值

python - 高级 Python pandas reshape

python - quit 函数在 try-except block 中不起作用

python - 异常后如何重试?

python - 查找列表的唯一组合的最快方法

java - 使用迭代器模式java使用一个循环打印出两个数据结构