且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查什么文件在Python中打开

更新时间:2023-11-25 15:45:10

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

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