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ロジックを個別の関数に分割し、ブロック内で1つずつ呼び出すことができます。

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 に答える