2012-06-25 72 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