本文介绍了是object .__ del __(self)最适合刷新日志记录类的地方吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的Python脚本提供了一个自定义日志记录类,该类具有 flush()方法,其中方法 print() s

I have a custom logging class for my Python script with a flush() method which print()s the contents of a list.

我想在特殊的 flush() > __ del __()方法,以防程序在没有刷新日志的情况下结束。但是中的注释指出:

I would like to include flush() in the special __del__() method in case the program ends without the log being flushed. However a note in the documentation states:

有人会建议采用其他方法吗?如果是,为什么?

Would anyone recommend a different way of doing this, and if so, why?

推荐答案

您可能需要考虑使此记录器成为。在异常终止的情况下,这仍然不会消失,但是几乎没有。但是即使在正常终止时,也可能不会在对象上调用 __ del __

You might want to look into making this logger a context manager. That still will not flush in the case of abnormal termination, but few things will. But __del__ might not be called on objects even in normal termination.

记录器可能是其中之一使用 with 语句时不太合适,因为它们非常全局,因此不确定上下文管理器是否合适。

Loggers might be one of the things that doesn't fit well when using the with statement, as they are quite global, so it's not sure context manager is a good fit.

这篇关于是object .__ del __(self)最适合刷新日志记录类的地方吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 00:30
查看更多