Copying file descriptors

Didier Trosset didier-dot-trosset at acqiris.com
Fri Oct 6 07:14:50 EDT 2006


I am using the following code. It is used to spawn a new process (using 
popen) and to change the file handles so that subsequent writes to 
standard output with printf goes into this child process standard input.


   import os

   child_stdin = os.popen("cat -", "w")
   old_stdout = os.dup(1)
   os.close(child_stdin.fileno())

   print "foo"

   os.dup2(old_stdout, 1)
   os.close(old_stdout)



It works. But the results is:
   close failed: [Errno 9] Bad file descriptor
when I am using python 2.4. Note that python 2.3 did not output such an 
error.

I am guessing that upon ending the script, python tries to close 
child_stdin file object, whereas the underlying file descriptor has 
already been closed. Thus the error.

Does anyone knows what to do to avoir this error message?

Thanks
Didier



More information about the Python-list mailing list