我正在写一个类似于诊断程序的程序,该程序运行一个测试,然后基于那个做更多的测试,所以这些大部分都在`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'将会抛出异常。 –