编程语言
首页 > 编程语言> > python-将整个主循环包装在try..finally块中是否合理?

python-将整个主循环包装在try..finally块中是否合理?

作者:互联网

我已经在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.这使您可以在程序退出时为自动回调函数注册一个或多个函数.

话虽这么说,您所拥有的应该运作良好.

标签:try-finally,python-2-7,exception-handling,python
来源: https://codeday.me/bug/20191120/2043881.html