python不会将文件句柄释放到日志文件 [英] python does not release filehandles to logfile
问题描述
我有一个必须运行许多模拟运行的应用程序.我想设置一个日志记录机制,其中所有日志记录都记录在general.log中,而所有用于模拟运行的日志都进入run00001.log,....为此,我定义了一个Run类.在__init__()
中,为运行日志添加了一个新的文件句柄.
I have an application which has to run a number of simulation runs. I want to setup a logging mechanisme where all logrecords are logged in a general.log, and all logs for a simulation run go to run00001.log, .... For this I have defined a class Run. in the __init__()
a new filehandle is added for the runlog.
问题在于,运行的日志文件永远不会释放,因此,在运行了许多运行之后,可用句柄就用光了,运行崩溃了.
The problem is that the logfiles for the runs never get released, so after a number of runs the available handles are exhausted and the run crashes.
我已经设置了一些例程来对此进行测试,如下所示:
I've set up some routines to test this as follows
主程序
import Model
try:
myrun = Model.Run('20130315150340_run_49295')
ha = raw_input('enter')
myrun.log.info("some info")
except:
traceback.print_exc(file=sys.stdout)
ha = raw_input('enter3')
Run类在模块Model中定义如下
The class Run is defined in module Model as follows
import logging
class Run(object):
""" Implements the functionality of a single run. """
def __init__(self, runid):
self.logdir="."
self.runid = runid
self.logFile = os.path.join(self.logdir , self.runid + '.log')
self.log = logging.getLogger('Run'+self.runid)
myformatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
myhandler = logging.FileHandler(self.logFile)
myhandler.setLevel(logging.INFO)
myhandler.setFormatter(myformatter)
self.log.addHandler(myhandler)
然后,我使用程序进程浏览器来跟踪文件处理程序.而且我看到运行日志出现了,但从未消失.
Then I use the program process explorer to follow the filehandlers. And I see the runlogs appear, but never disappear.
有没有办法强制执行此操作?
Is there a way I can force this?
推荐答案
您需要在文件处理程序上调用.close()
.
You need to call .close()
on the filehandler.
Run
类完成后,请致电:
handlers = self.log.handlers[:]
for handler in handlers:
handler.close()
self.log.removeHandler(handler)
这篇关于python不会将文件句柄释放到日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!