[IPython-dev] Fwd: IPython and closing sys.stdout

Fernando Perez Fernando.Perez at colorado.edu
Wed Sep 27 03:24:23 EDT 2006


[ Skip, thanks for this, I'm forwarding it to ipython-dev which is subscriber 
only (too much spam).]


Subject:IPython and closing sys.stdout
From:skip at pobox.com
Date:Thu, 21 Sep 2006 14:46:48 -0500
To:ipython-dev at scipy.org

John Hunter alerted me to a segfault problem in code.InteractiveConsole when
sys.stdout is closed.  This problem is present in Python up to 2.4.3 as far
as I can tell, but is fixed in later versions of Python (2.5, 2.4.4 when
it's released, svn trunk).  Even with that fix, if the user calls
sys.stdout.close() you'll get a ValueError and your console will be useless.
I took a look at the code in Python that the InteractiveConsole class
exercises and see that the cause is that the naive raw_input() method simply
calls the raw_input() builtin.  That function gets the "stdin" and "stdout"
functions from the sys module and there's no way to override that behavior.

In my opinion, the best thing to do would be to subclass InteractiveConsole
and provide a more robust raw_input() method.  Ideally, I think you'd want
to dup() the file descriptors for sys.{stdin,stdout} and use those instead
of calling the builtin raw_input().  Something like (untested):

     class IC(code.InteractiveConsole):
         def __init__(self):
             code.InteractiveConsole.__init__(self)
             self.input = os.fdopen(os.dup(sys.stdin.fileno()))
             self.output = os.fdopen(os.dup(sys.stdout.fileno()))
             self.error = os.fdopen(os.dup(sys.stderr.fileno()))

         def raw_input(self, prompt=""):
             if prompt:
                 self.output.write(prompt):
                 self.output.flush()
             return self.input.readline()

         def write(self, data):
             self.error.write(data)

Also, the runcode() method will have to be overridden to use self.output
instead of sys.stdout.  Those couple changes should (hopefully) insulate
IPython from such user wackiness.

Skip Montanaro
skip at pobox.com

-------------- next part --------------
An embedded message was scrubbed...
From: skip at pobox.com
Subject: IPython and closing sys.stdout
Date: Thu, 21 Sep 2006 14:46:48 -0500
Size: 2955
URL: <http://mail.python.org/pipermail/ipython-dev/attachments/20060927/f54d5fec/attachment.eml>


More information about the IPython-dev mailing list