我在Python2.7.9中为一个小项目制作了一个地图编辑器,我正在寻找在发生未处理的异常时保留我编辑的数据的方法。我的编辑器已经有了一个保存数据的方法,我当前的解决方案是将主循环包装在一个try..finally块中,类似于以下示例:

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.

这似乎是最好的方法,以确保无论发生什么,在编辑器应该崩溃的情况下,都会尝试保持编辑器的当前状态(只要saveFile()已经准备好这样做)。但我想知道,将整个主循环封装在一个try块中是否确实是安全、高效和良好的形式。它是?是否存在风险或问题?有更好或更传统的方法吗?

最佳答案

如果你的文件不是那么大,我建议你把整个输入文件读入内存,关闭文件,然后在内存中的副本上进行数据处理,这将解决你在不损坏数据的同时可能会降低运行时间的问题。
或者,看看atexit python module。这允许您在程序退出时注册一个自动回调函数的函数。
那就是说你所拥有的应该是相当有效的。

09-03 22:28