How to close file descriptors in python?


I have the following code in python:

import os class suppress_stdout_stderr(object): ''' A context manager for doing a "deep suppression" of stdout and stderr in Python, i.e. will suppress all print, even if the print originates in a compiled C/Fortran sub-function. This will not suppress raised exceptions, since exceptions are printed to stderr just before a script exits, and after the context manager has exited (at least, I think that is why it lets exceptions through). ''' def __init__(self): # Open a pair of null files self.null_fds = [os.open(os.devnull,os.O_RDWR) for x in range(2)] # Save the actual stdout (1) and stderr (2) file descriptors. self.save_fds = (os.dup(1), os.dup(2)) def __enter__(self): # Assign the null pointers to stdout and stderr. os.dup2(self.null_fds[0],1) os.dup2(self.null_fds[1],2) def __exit__(self, *_): # Re-assign the real stdout/stderr back to (1) and (2) os.dup2(self.save_fds[0],1) os.dup2(self.save_fds[1],2) # Close the null files os.close(self.null_fds[0]) os.close(self.null_fds[1]) for i in range(10**6): with suppress_stdout_stderr(): print 'plop' if i % 50 == 0: print i

it fails at 5100 on OSX with OSError: [Errno 24] Too many open files. I'm wondering why and if there is a solution to close the file descriptor. I'm looking for a solution for a context manager which closes stdout and stderr.


I executed your code on a Linux machine and got the same error but at a different number of iterations. I added the following two lines in the __exit__(self, *_) function of your class:

os.close(self.save_fds[0]) os.close(self.save_fds[1])

With this change I do not get an error and the script returns successfully. I assume that the duplicated file descriptors stored in self.save_fds are kept open if you don't close them with os.close(fds) and so you get the too many files open error. Anyway my console printed "plop", but maybe this depends on my platform. Let me know if it works :)



  • Simple chat system over websockets with reconnection feature
  • google translate not showing up when https is used in url
  • php string comparison unexpected type juggling
  • How can I resolve this SQLTransactionRollbackException with Hsqldb in Spring Batch?
  • Graphics using Standard C++ only?
  • Windows SDK UWP App Error - DEP3321
  • F# / .NET null instance oddity
  • How to manage sub-domains on WinHost with IIS7 URL Rewrite 2.0?
  • Oracle: split string to rows
  • IdHttp Post Method Delphi 2010
  • Calling a jQuery method named in variable
  • Jquery call of Java RESTful service not working CORS
  • When using Shibboleth (v3) as SP , can I map the attribute value in attribute-map.xml?
  • Is the Windows App Store required for a UWP application?
  • Iterating through a folder using batch script
  • unicode characters in html
  • Read specific column from Parquet without using Spark
  • Webdriver 3.14 IE11: session lost when click link/button that opens a window/popup
  • C++ How to get process ID from filename of DLL(windows)?
  • Can Node.JS on OpenShift be upgraded?
  • Use PHP to Replace HTML with HTML
  • How to get the Owner of the ContextMenu (from Silverlight 4 toolkit)?
  • Get name of days between two date in ios?
  • Checking for valid enum types from protobufs
  • how to add dashed border on highcharts “area” graph for every point
  • How to use Typescript with libraries like Ampersand.js that parse configs to build prototypes
  • Add checkbox dynamically using angular 2
  • 'Edit' function for forum posts and such
  • how to run a different select statement based on condition in Hive SQL
  • How to write seo friendly url's using htaccess?
  • Django, uWSGI & nginx: Process dies for “no reason”
  • using maven pom while creating jar:test-jar some times it says JAR will be empty - no content was ma
  • VS2010 RDLC C#. How can I set a LocalReport object to a ReportViewer?
  • Why is ordered choice in pyparsing failing for my use case?
  • JQuery: Infinite input select
  • Neo4j…how to get a visual representation of my data?
  • Background transfer download task failed when app was closed
  • ssh remote server login script
  • Using Service Component Runtime
  • Write to .csv file with PHP (Commas in Data Error)