Claudiu Claudiu - 1 year ago 71
Python Question

check what files are open in 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?

Answer Source

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)

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

def printOpenFiles():
    print "### %d OPEN FILES: [%s]" % (len(openfiles), ", ".join(f.x for f in openfiles))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download