python下logging库之shutdown
2020-04-21 本文已影响0人
MrSunday_8955
一种场景:python开发中使用logging库记录日志信息。在程序结束前需要将日志转存到一个备份存储并删除现有日志。但是删除日志时通常会报错,错误如下:
python.exe test.py
Traceback (most recent call last):
File "C:/Users/sunday/Desktop/test/test.py", line 58, in <module>
os.remove(log_file)
PermissionError: [WinError 32] 另一个程序正在使用此文件,进程无法访问。: 'C:\\Users\\sunday\\Desktop\\test\\test.log'
无法删除的原因就是logging没有释放日志文件的句柄,造成没权限删除。这时候logging库的shutdown就派上用场。查看shutdown源码可以看到shutdown就是用于程序退出前被使用。
def shutdown(handlerList=_handlerList):
"""
Perform any cleanup actions in the logging system (e.g. flushing
buffers).
Should be called at application exit.
"""
for wr in reversed(handlerList[:]):
#errors might occur, for example, if files are locked
#we just ignore them if raiseExceptions is not set
try:
h = wr()
if h:
try:
h.acquire()
h.flush()
h.close()
except (OSError, ValueError):
# Ignore errors which might be caused
# because handlers have been closed but
# references to them are still around at
# application exit.
pass
finally:
h.release()
except: # ignore everything, as we're shutting down
if raiseExceptions:
raise
#else, swallow
#Let's try and shutdown automatically on application exit...
import atexit
atexit.register(shutdown)
删除日志文件前加上shutdown,完美退出。
logging.shutdown()
os.remove(log_file)
执行:
python.exe test.py
进程已结束,退出代码 0