好的,我找到了最适合我的答案:
import sys
try:
print "any code: allocate files, usb gadets etc "
try:
sys.exit(-1) # some severe error occure
except Exception as e:
print "sys.exit is not catched:"+str(e)
finally:
print "but all sub finallies are done"
print "shall not be executed when sys.exit called before"
finally:
print "Here we can properly free all resources in our preferable order"
print "(ie close log file at the end after closing all gadgets)"
至于推荐的解决方案 atexit - 它会很好,但它在我的 python 2.6 中不起作用。我试过这个:
import sys
import atexit
def myFinal():
print "it doesn't print anything in my python 2.6 :("
atexit.register(myFinal)
print "any code"
sys.exit(-1) # is it pluged in?
print "any code - shall not be execute"
至于 Wrapper 解决方案 - 它绝对是最花哨的 - 但老实说,我不能说它有多好......
import sys
class mainCleanupWrapper(object):
def __enter__(self):
print "preallocate resources optionally"
def __exit__(self, type, value, traceback):
print "I release all resources in my order"
with mainCleanupWrapper() as whatsThisNameFor:
print "ok my unchaged code with any resources locking"
sys.exit(-1)
print "this code shall not be executed"
我找到了我的解决方案 - 但坦率地说,python 似乎变得非常庞大和臃肿......