[New-bugs-announce] [issue24595] InteractiveInterpreter always prints to stdout

Anton Astafiev report at bugs.python.org
Thu Jul 9 15:00:12 CEST 2015


New submission from Anton Astafiev:

I have a use-case when I need to forward InteractiveConsole through Unix/TCP socket. Expected implementation:

class InteractiveSocket(InteractiveConsole):
  def __init__(self, socket):
    self._socket = socket
    ...

  def raw_input(...):
    # read from socket

  def write(...):
    # write to socket

However, only syntax errors and tracebacks are written into a socket, while actual output still appears on servers stdout. Digging through it I realized, that the output happens inside exec call in InteractiveInterpreter.runcode and here is why:

>>> c=compile('42', '', 'single')
>>> dis.dis(c)
<<< 1           0 LOAD_CONST               0 (42)
                3 PRINT_EXPR          
                4 LOAD_CONST               1 (None)
                7 RETURN_VALUE

where PRINT_EXPR uses _Py_IDENTIFIER(displayhook);

I ended up with the following dirty hack in my derived class:

def runcode(self, code):
  class OutWriter:
    pass
  writer = OutWriter()
  writer.write = self.write
  old = sys.stdout
  sys.stdout = writer
  try:
    exec(code, self.locals)
  except SystemExit:
    raise
  except:
    self.showtraceback()
  sys.stdout = old

I think it would be nice to make InteractiveInterpreter extendable out of the box, though I don't have exact solution here.

----------
components: Library (Lib)
messages: 246487
nosy: Anton Astafiev
priority: normal
severity: normal
status: open
title: InteractiveInterpreter always prints to stdout
type: behavior

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue24595>
_______________________________________


More information about the New-bugs-announce mailing list