python文件句柄_python不会将文件句柄释放到日志文件

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

main routine

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')

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?

解决方案

You need to call .close() on the filehandler.

When your Run class completes, call:

handlers = self.log.handlers[:]

for handler in handlers:

handler.close()

self.log.removeHandler(handler)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值