reducing the number of try,except in python
-
16-06-2021 - |
Question
I'm writing a program similar to a diagnostic program , that runs a test and then based on that do more tests, so most of these are done inside `try,except
and there are quite a lot of them. Is there any other way to achieve this but reduce the number of try except
?
Here is a sample code.
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"
The same code above (with different file names) repeat and I know that it's not a good practice to do that. I'm pretty new to python and googling didn't give any helpful results.
Solution
You can split your logic into separate functions and call them one by one in a try
block:
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))
where "catch" a tuple of exceptions you want to handle.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow