Python 使用RotatingFileHandler和subprocess.Popen时出现Windows错误

Python 使用RotatingFileHandler和subprocess.Popen时出现Windows错误,python,subprocess,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

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