gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:31:58 24 4
gpt4 key购买 nike

我的代码使用了 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com