[英]How to catch all exceptions in Try/Catch Block Python?
我正在編寫python代碼來安裝我的程序在linux環境中所需的所有庫包。所以linux可能包含python 2.7或2.6或兩者,所以我開發了一個try和除了塊代碼,將在linux中安裝pip包。 嘗試塊代碼包含python 2.7版本pip install和Catch塊包含python 2.6版本pip install。 我的問題是代碼的和平工作正常,當我試圖在python 2.6中安裝pandas它讓我有些錯誤。 我想抓住那個例外。 你能否告訴我如何改進我的嘗試,除了塊以捕獲該異常
required_libraries = ['pytz','requests','pandas']
try:
from subprocess import check_output
pip27_path = subprocess.check_output(['sudo','find','/','-name','pip2.7'])
lib_installs = [subprocess.call((['sudo',pip27_path.replace('\n',''),'install', i])) for i in required_libraries]
except:
p = subprocess.Popen(['sudo','find','/','-name','pip2.6'], stdout=subprocess.PIPE);pip26_path, err = p.communicate()
lib_installs = [subprocess.call((['sudo',pip26_path.replace('\n',''),'install', i])) for i in required_libraries]
您可以使用一個塊捕獲幾個異常。 讓我們對異常使用Exception和ArithmeticError。
try:
# Do something
print(q)
# Catch exceptions
except (Exception, ArithmeticError) as e:
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
message = template.format(type(e).__name__, e.args)
print (message)
如果您需要捕獲幾個異常並自己處理每個異常,那么您將為每個異常編寫一個except語句。
try:
# Do something
print(q)
# Catch exceptions
except Exception as e:
print (1)
except ArithmeticError as e:
print (2)
# Code to be executed if the try clause succeeded with no errors or no return/continue/break statement
else:
print (3)
您還可以檢查異常是否為“MyCustomException”類型,例如使用if語句。
if isinstance(e, MyCustomException):
# Do something
print(1)
至於你的問題,我建議將代碼分成兩個函數。
install(required_libraries)
def install(required_libraries, version='pip2.7'):
# Perform installation
try:
from subprocess import check_output
pip27_path = subprocess.check_output(['sudo','find','/','-name', version])
lib_installs = [subprocess.call((['sudo',pip27_path.replace('\n',''),'install', i])) for i in required_libraries]
except Exception as e:
backup(required_libraries)
def backup(required_libraries, version='pip2.6'):
try:
p = subprocess.Popen(['sudo','find','/','-name',version]], stdout=subprocess.PIPE);pip26_path, err = p.communicate()
lib_installs = [subprocess.call((['sudo',pip26_path.replace('\n',''),'install', i])) for i in required_libraries]
except Exception as e:
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
message = template.format(type(e).__name__, e.args)
print (message)
#Handle exception
注意:我沒有測試過這個,我也不是專家,所以我希望我能提供幫助。
有用的鏈接:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.