Python:登录后无法删除文件

7

我正在使用以下代码将日志写入文件:

import logging
from gmplot import gmplot
logging.basicConfig(filename="sample.log", level=logging.INFO)
logging.debug("This is a debug message")
logging.info("Informational message")
logging.error("An error has happened!")

但是现在无法删除这个文件。我该如何“释放”这个文件呢?
2个回答

7
你需要关闭日志记录:
如下所述: python does not release filehandles to logfile 当你的“Run”类完成时,请调用:
handlers = self.log.handlers[:]
for handler in handlers:
    handler.close()
    self.log.removeHandler(handler)

1
在问题示例中,必须关闭的处理程序是什么? - dylanvanw
如果 handlers 为空,则将第一个 self.log 替换为 logging.getLogger(),而不是 logging.getLogger(__name__) - Nixinova

4

当您完成日志记录时,只需使用logging.shutdown()。


这是解决在这里遇到PermissionError问题的方法。 - eric

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接