python - 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
解决方案
基于python 文档,try-except 可以采用可选的 else 语句:
try ... except 语句有一个可选的 else 子句,当它出现时,它必须跟在所有 except 子句之后。如果 try 子句不引发异常,则它对于必须执行的代码很有用。
因此,基于此,如果 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
推荐阅读
- javascript - 使用 ES6 解构简化 javascript 对象创建
- php - 带有oracle客户端11g的php
- angularjs - 视图中的图形不显示 - Chart.js Angularjs
- java - JAVA API 不返回任何结果。在服务器上运行的 SQL 查询确实
- r - 在 R lmer() 中组合多个变量的 BLUP 估计
- character-encoding - 不显示区域 (UTF-8) 字符的可操作消息
- javascript - Firefox 是否可以使用 Google 一键式登录?
- javascript - Callbacks for navigator.geolocation.getCurrentPosition are not firing in firefox
- android - 离子科尔多瓦运行android失败
- javascript - 使用 @ts-check 在 JS 文件中键入断言元素