使用基于时间的旋转文件处理程序时出现错误
os.rename('logthred.log', dfn)
WindowsError: [Error 32] The process cannot access the file because it
is being used by another process
配置:
[loggers]
keys=root
[logger_root]
level=INFO
handlers=timedRotatingFileHandler
[formatters]
keys=timedRotatingFormatter
[formatter_timedRotatingFormatter]
format = %(asctime)s %(levelname)s %(name)s.%(functionname)s:%(lineno)d %
(output)s
datefmt=%y-%m-%d %H:%M:%S
[handlers]
keys=timedRotatingFileHandler
[handler_timedRotatingFileHandler]
class=handlers.TimedRotatingFileHandler
level=INFO
formatter=timedRotatingFormatter
args=('D:\\log.out', 'M', 2, 0, None, False, False)
想要实现基于时间的旋转文件处理程序,并且多个进程可以写入同一个日志文件。在 python 中,我没有找到任何可以帮助解决这个问题的东西。
我已阅读有关此问题的讨论 (python issues)。
任何可以解决这个问题的建议。
最佳答案
找到解决方案:Python 2.7 中的问题每当我们创建子进程时,父进程的文件句柄也由子进程继承,因此这会导致错误。我们可以使用这段代码来阻止这种继承。
import sys
from ctypes import windll
import msvcrt
import __builtin__
if sys.platform == 'win32':
__builtin__open = __builtin__.open
def __open_inheritance_hack(*args, **kwargs):
result = __builtin__open(*args, **kwargs)
handle = msvcrt.get_osfhandle(result.fileno())
if filename in args: # which filename handle you don't want to give to child process.
windll.kernel32.SetHandleInformation(handle, 1, 0)
return result
__builtin__.open = __open_inheritance_hack
关于windows - 用于日志记录的基于 Python 时间的旋转文件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45791358/