我正在寫一個類似於診斷程序的程序,該程序運行一個測試,然後基於那個做更多的測試,所以這些大部分都在`try,except
之內完成,並且有相當多的他們中的很多。有沒有其他方法可以達到這個目的,但減少try except
的數量?減少嘗試的次數,除了python
這裏是一個示例代碼。
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搜索沒有給出任何有用的結果。
您不需要打開'helloworld.exe'來執行它。另外,您是否希望程序在遇到錯誤時繼續執行? –
我沒有打開程序,我正在檢查程序是否存在,是否打開,是的,我希望程序執行下一個測試,即使這個程序失敗了,這個打印結果在非常結束,比如哪一個失敗併成功。 – cyberbemon
您正在打開該程序。沒有必要;如果程序不存在,'subprocess.call'將會拋出異常。 –