Finding count of currently open file descriptors.

Holden Caulfield phoebe_1 at
Thu Aug 1 17:15:00 CEST 2002

Tim McNerney <tmcnerney at> wrote in message news:<3D469D2F.6010003 at>...
> How do I go about finding out the number of file descriptors currently 
> open in a program? I'm trying to track down a file descriptor leak which 
> may or may not be in library calls. Will I run into problems getting an 
> accurate count due to the possible delay between doing a close and GC?
> Thanks.
> --Tim

This is part of the snippet of code, that I use, you can change it to
your needs:

from errno import EBADF
  import os
  max_fds = os.sysconf('SC_OPEN_MAX')
except (ValueError),(e):
  print "oh well, go the C route"
  for fd in xrange(3,max_fds):
         os.close(fd)    # or do anything else to check if fd is valid
     except (OSError),(e):
         if e.errno == EBADF:
             print "non existent fd"
             print "something really messed up"

Obviously, I am ignoring the stdin,stdout and stderr in the xrange.
Also, this might only work in UNIX.
Dave's C solution might be faster as he said.

More information about the Python-list mailing list