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 <rep...@bugs.python.org>
<http://bugs.python.org/issue24595>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to