2012-06-25 73 views
1

我正在寫一個類似於診斷程序的程序,該程序運行一個測試,然後基於那個做更多的測試,所以這些大部分都在`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搜索沒有給出任何有用的結果。

+1

您不需要打開'helloworld.exe'來執行它。另外,您是否希望程序在遇到錯誤時繼續執行? –

+0

我沒有打開程序,我正在檢查程序是否存在,是否打開,是的,我希望程序執行下一個測試,即使這個程序失敗了,這個打印結果在非常結束,比如哪一個失敗併成功。 – cyberbemon

+0

您正在打開該程序。沒有必要;如果程序不存在,'subprocess.call'將會拋出異常。 –

回答

4

您可以將邏輯分成不同的功能,並在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)) 

其中「釣」你要處理異常的元組。

+0

目前有14個try catch異常(我知道,非常糟糕!),我會繼續努力。 – cyberbemon

+0

except語句的語法應該是「except(OSError,IOError),e」,否則它只會捕獲OSError實例並將它們綁定到名稱「IOError」。此外,至少打印錯誤消息可能會更好 - 並且如果任何步驟取決於前面步驟的結果,則可能不會進一步嘗試(如果情況如此,最佳異常處理方案也不例外根本處理)。 –

+0

@brunodesthuilliers:很好,謝謝。 – georg