On 2015-05-19, Skip Montanaro <skip.montan...@gmail.com> wrote:
> Yeah, I'm still on 2.7, and am aware of PEP 446. Note that many of the file
> descriptors will not have been created by my Python code. They will have
> been created by underlying C/C++ libraries, so I can't guarantee which
> flags were set on file open.

There is no portable way to do this, the problem is Unix not Python.
The below code is a reasonable stab at it, but there is no 100%
guaranteed method. The code is untested but you get the idea.


  import errno
  import os


  def closeall(min=0, max=4096, keep=frozenset()):
      """Close all open file descriptors except for the given exceptions.

      Any file descriptors below or equal to `min`, or in the set `keep`
      will not be closed. Any file descriptors above `max` *might* not be
      closed.
      """
      # First try /proc/$$/pid
      try:
          for fd in os.listdir("/proc/%d/fd" % (os.getpid())):
              try:
                  fd = int(fd)
              except ValueError:
                  continue
              if fd >= min and fd not in keep:
                  os.close(int(fd))
          return
      except OSError as exc:
          if exc[0] != errno.ENOENT:
              raise
      # If /proc was not available, fall back to closing a lot of descriptors.
      for fd in range(min, max):
          if fd not in keep:
              try:
                  os.close(fd)
              except OSError as exc:
                  if exc[0] != errno.EBADF:
                      raise
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to