将整个主循环包装在 try..finally 块中是否合理?
Is it reasonable to wrap an entire main loop in a try..finally block?
我已经在 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
块中是可接受的模式,当您需要发生某些事情时无论如何。在某些情况下,它会记录并继续,在其他情况下,它会保存所有可能的内容并退出。
所以你的代码没问题。
我已经在 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
块中是可接受的模式,当您需要发生某些事情时无论如何。在某些情况下,它会记录并继续,在其他情况下,它会保存所有可能的内容并退出。
所以你的代码没问题。