You could redirect the stdout temporarily:
import code
import sys
from contextlib import contextmanager
try:
from StringIO import StringIO
except ImportError: # Python 3
from io import StringIO
try:
from contextlib import redirect_stdout
except ImportError: # Python < 3.4
@contextmanager
def redirect_stdout(new_target):
old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
try:
yield new_target # run some code with the replaced stdout
finally:
sys.stdout = old_target # restore to the previous value
f = StringIO()
with redirect_stdout(f):
console = code.InteractiveConsole()
console.push('print("hello world")')
console.push('i = int(input("give me a number"))')
console.push('sq = i*i')
console.push('print("%d squared is %d" % (i, sq))')
print("Got: %r" % f.getvalue())
Example:
$ echo 2 | python code-interactive.py
Got: 'hello world\ngive me a number2 squared is 4\n'