一種場景:python開發(fā)中使用logging庫記錄日志信息。在程序結(jié)束前需要將日志轉(zhuǎn)存到一個備份存儲并刪除現(xiàn)有日志。但是刪除日志時通常會報錯,錯誤如下:
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] 另一個程序正在使用此文件,進(jìn)程無法訪問。: 'C:\\Users\\sunday\\Desktop\\test\\test.log'
無法刪除的原因就是logging沒有釋放日志文件的句柄,造成沒權(quán)限刪除。這時候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)
執(zhí)行:
python.exe test.py
進(jìn)程已結(jié)束,退出代碼 0