Is it possible to wrap the entire main loop in a try..finally block?

I have created a map editor in Python2.7.9

for a small project and I am looking for ways to save the data I am editing in case of any unhandled exception. My editor already has a method to save the data, and my current solution is that the main loop wrapped in a block try..finally

is like this example:

import os, datetime #..and others.
if __name__ == '__main__':
    DataMgr = DataManager() # initializes the editor.
    save_note = None
    try:
        MainLoop()  # unsurprisingly, this calls the main loop.
    except Exception as e: # I am of the impression this will catch every type of exception.
        save_note = "Exception dump: %s : %s." % (type(e).__name__, e) # A memo appended to the comments in the save file.
    finally:
        exception_fp = DataMgr.cwd + "dump_%s.kmap" % str(datetime.datetime.now())
        DataMgr.saveFile(exception_fp, memo = save_note) # saves out to a dump file using a familiar method with a note outlining what happened.

      

This seems like the best way to make sure that no matter what happens, an attempt is made to preserve the current state of the editor (to the extent that it is saveFile()

equipped to do so) in case it crashes, but I'm wondering if encapsulating my main loop into a block is really try

safe , effective and correct. It? Are there risks or problems? Is there a better or more conventional way?

+3


source to share


2 answers


If your file is not that big, I would suggest perhaps reading the entire input file into memory, close the file, and then doing data processing on a copy in memory, this will fix any problems you have without damaging your data at the expense of possible slowing down the execution time.

Alternatively, have a look at the atexit python module . This allows you to register the function (s) for an automatic callback function when the program exits.



Speaking of which, you have to work well enough.

+1


source


Wrapping the main loop in a block try...finally

is the accepted pattern for when you need to get something going no matter what. In some cases, it logs in and continues, while in others, it saves its best and leaves.



So you - the code is fine.

+2


source







All Articles