Python everything in try block
I am writing a large batch-type script in Python, and need to do some cleanup in the end, regardless of whether an exception occurred. To do this I'm simply putting the main program in a try block and the cleanup in a finally block.
This seems to work well, but my question is how to print any exceptions that might occur. Currently it just 开发者_如何转开发ignores them and jumps to the finally block.
You should just be able to use a try
/finally
block with no exception handler. It won't catch the exception or suppress the traceback, just ensure your cleanup code is run whether or not there is an exception. That's the entire point of finally
.
Here's an example:
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> try:
... print 'begin try'
... assert False
... print 'end try'
... finally:
... print 'finally'
...
begin try
finally
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
AssertionError
you can use traceback.
something like:
import traceback
try:
foo
except:
print(traceback.format_exc())
finally:
cleanup
精彩评论