1

我正在编写一个类似于诊断程序的程序,它运行一个测试,然后在此基础上做更多的测试,所以大部分都是在内部完成的,`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 很陌生,谷歌搜索没有给出任何有用的结果。

4

1 回答 1

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))

在哪里“捕获”您要处理的异常元组。

于 2012-06-25T09:30:26.573 回答