[英]reducing the number of try,except in python
我正在編寫一個類似於診斷程序的程序,它運行一個測試,然后基於那個做更多的測試,因此大多數這些都在`try,except
中完成`try,except
並且有很多它們。 有沒有其他方法來實現這一點,但減少try except
?
這是一個示例代碼。
try:
treeinfo = subprocess.check_output(['C:\Python27\Scripts\scons.bat','-f' ,'scons_default.py' ,'--tree=all'])
print "\n"
print "Your machine type is ",platform.machine()
print "Compiling using default compiler\n"
print treeinfo
except subprocess.CalledProcessError as e:
print "ERROR\n"
try:
with open ('helloworld.exe')as f:
subprocess.call('helloworld.exe')
print"Build success"
log64 = subprocess.check_output(["dumpbin", "/HEADERS", "helloworld.exe"])
if arch64 in log64:
print "Architecture of the compiled file is 64-bit "
elif arch32 in log64:
print "Architecture of the compiled file is 32-bit"
except IOError as e:
print "Build failed\n"
print "\n"
上面的相同代碼(具有不同的文件名)重復,我知道這樣做不是一個好習慣。 我對python很新,google搜索沒有給出任何有用的結果。
您可以將邏輯拆分為單獨的函數,並在try
塊中逐個調用它們:
def a():
treeinfo = subprocess.check_output(['C:\Python27\Scripts\scons.bat','-f' ,'scons_default.py' ,'--tree=all'])
print "\n"
print "Your machine type is ",platform.machine()
print "Compiling using default compiler\n"
print treeinfo
def b():
subprocess.call('helloworld.exe')
print"Build success"
def c():
log64 = subprocess.check_output(["dumpbin", "/HEADERS", "helloworld.exe"])
if arch64 in log64:
print "Architecture of the compiled file is 64-bit "
elif arch32 in log64:
print "Architecture of the compiled file is 32-bit"
def try_these(funs, catch):
for fun in funs:
try:
fun()
except catch:
print 'ERROR!'
try_these([a, b, c], catch=(IOError, OSError))
在哪里“捕獲”你想要處理的異常元組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.