python3 logging 句柄释放 shutdown 简介

ゝ一纸荒年。 2022-08-28 10:52 40阅读 0赞

一种场景:python开发中使用logging库记录日志信息。在程序结束前需要将日志转存到一个备份存储并删除现有日志。但是删除日志时通常会报错,错误如下:

  1. python.exe test.py
  2. Traceback (most recent call last):
  3. File "C:/Users/sunday/Desktop/test/test.py", line 58, in <module>
  4. os.remove(log_file)
  5. PermissionError: [WinError 32] 另一个程序正在使用此文件,进程无法访问。: 'C:\\Users\\sunday\\Desktop\\test\\test.log'

无法删除的原因就是logging没有释放日志文件的句柄,造成没权限删除。这时候logging库的shutdown就派上用场。查看shutdown源码可以看到shutdown就是用于程序退出前被使用。

  1. def shutdown(handlerList=_handlerList):
  2. """
  3. Perform any cleanup actions in the logging system (e.g. flushing
  4. buffers).
  5. Should be called at application exit.
  6. """
  7. for wr in reversed(handlerList[:]):
  8. #errors might occur, for example, if files are locked
  9. #we just ignore them if raiseExceptions is not set
  10. try:
  11. h = wr()
  12. if h:
  13. try:
  14. h.acquire()
  15. h.flush()
  16. h.close()
  17. except (OSError, ValueError):
  18. # Ignore errors which might be caused
  19. # because handlers have been closed but
  20. # references to them are still around at
  21. # application exit.
  22. pass
  23. finally:
  24. h.release()
  25. except: # ignore everything, as we're shutting down
  26. if raiseExceptions:
  27. raise
  28. #else, swallow
  29. #Let's try and shutdown automatically on application exit...
  30. import atexit
  31. atexit.register(shutdown)

删除日志文件前加上shutdown,完美退出。

  1. logging.shutdown()
  2. os.remove(log_file)
  3. 执行:
  4. python.exe test.py
  5. 进程已结束,退出代码 0

发表评论

表情:
评论列表 (有 0 条评论,40人围观)

还没有评论,来说两句吧...

相关阅读