运行 Windows 7 和 Python 2.7.8,使用 RotatingFileHandler 进行日志记录,并使用 subprocess.Popen 使得 RotatingFileHandler 无法在 Popen 之后旋转其文件。给定代码:
import subprocess
import logging
from logging.handlers import RotatingFileHandler
handler=RotatingFileHandler('log.txt', maxBytes=100, backupCount=10)
logger=logging.getLogger()
logger.setLevel(logging.INFO)
logger.addHandler(handler)
logger.info('before Popen')
s=subprocess.Popen('notepad')
logger.info('after Popen')
我得到错误:
python t.py
Traceback (most recent call last):
File "c:\prog64\Python27\lib\logging\handlers.py", line 77, in emit
self.doRollover()
File "c:\prog64\Python27\lib\logging\handlers.py", line 142, in doRollover
os.rename(self.baseFilename, dfn)
WindowsError: [Error 32] The process cannot access the file because it is being used by another process
Logged from file t.py, line 11
.
请您参考如下方法:
问题原来是用于日志文件的文件描述符在调用 Popen 之前没有关闭。
在上面的例子中,notepad 的执行不依赖于打开的文件描述符。这些可以用 Popen 的 close_fds=True 参数关闭,编码为:
s=subprocess.Popen('notepad', close_fds=True)
或者,当子进程确实依赖于打开的文件描述符,但不使用记录器时,通过调用关闭记录器文件就足够了:
handler.close()
就在调用 subprocess.Popen 之前。
