わかりました、私に最も適した答えを見つけました:
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はかなりかさばって肥大化しているようです...