WindowsError使用RotatingFileHandler和subprocess.Popen

时间:2015-03-23 21:07:51

标签: python subprocess

运行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

1 个答案:

答案 0 :(得分:1)

问题是,在调用Popen之前,没有关闭用于日志文件的文件描述符。

在上面的示例中,notepad的执行不依赖于打开的文件描述符。这些可以用Popen的close_fds = True参数关闭,编码为:

s=subprocess.Popen('notepad', close_fds=True)

或者,当子进程确实依赖于打开文件描述符但不使用记录器时,只需通过调用以下命令关闭记录器文件就足够了:

handler.close()

在致电subprocess.Popen之前。