检查什么文件在Python中打开 [英] check what files are open in Python

查看:66
本文介绍了检查什么文件在Python中打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在程序中收到一个错误,该程序应该运行很长时间,打开的文件太多。有没有什么方法可以跟踪哪些文件是打开的,所以我可以偶尔打印该列表,看看问题在哪里?

I'm getting an error in a program that is supposed to run for a long time that too many files are open. Is there any way I can keep track of which files are open so I can print that list out occasionally and see where the problem is?

推荐答案

我最终将内置的文件对象包装在我的程序的入口点。我发现我没有关闭我的记录器。

I ended up wrapping the built-in file object at the entry point of my program. I found out that I wasn't closing my loggers.

import __builtin__
openfiles = set()
oldfile = __builtin__.file
class newfile(oldfile):
    def __init__(self, *args):
        self.x = args[0]
        print "### OPENING %s ###" % str(self.x)            
        oldfile.__init__(self, *args)
        openfiles.add(self)

    def close(self):
        print "### CLOSING %s ###" % str(self.x)
        oldfile.close(self)
        openfiles.remove(self)
oldopen = __builtin__.open
def newopen(*args):
    return newfile(*args)
__builtin__.file = newfile
__builtin__.open = newopen

def printOpenFiles():
    print "### %d OPEN FILES: [%s]" % (len(openfiles), ", ".join(f.x for f in openfiles))

这篇关于检查什么文件在Python中打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆