Carl Younger
Carl Younger

Reputation: 3080

Make Python's Interactive Interpreter Class Print Evaluated Expressions

When you use the Python Interactive Interpreter, you can enter an expression, say 1+1 and it'll print the value. If you write 1+1 in a script, it will not print anything, which makes perfect sense.

However, when you create a subclass of code.InteractiveInterpreter, then pass 1+1 into it, using the runcode method, it will not print 2, which makes less sense.

Does anyone know of a clean way to make an InteractiveInterpreter instance print the value of expressions?

Note: This needs to be pretty robust as the application provides a shell to users, and we all know what they're like.

Cheers

P.S. This is for a Python3 application, but a better Python2 solution will get the check.

Upvotes: 4

Views: 944

Answers (1)

Carl Groner
Carl Groner

Reputation: 4359

Isn't that what code.InteractiveConsole is for?

>>> import code
>>> console = code.InteractiveConsole()
>>> r = console.push('1+1')
2
>>> r = console.push('x = 4 + 1')
>>> r = console.push('x + 10')
15

>>> r = console.push('def test(n):')
>>> r = console.push('  return n + 5')
>>> r = console.push('')
>>> r = console.push('test(10)')
15

Or with embedded newlines:

>>> r = console.push('def test2(n):\n  return n+10\n')
>>> r = console.push('test2(10)')
20
>>>

# the following, however, fails...
>>> r = console.push('test(10)\ntest(15)')
  File "<console>", line 1
    test(10)
           ^
SyntaxError: multiple statements found while compiling a single statement
>>> 

Upvotes: 2

Related Questions