制作Python的交互式解释器类打印评估表达式

时间:2013-10-11 02:07:43

标签: python

当您使用Python Interactive Interpreter时,您可以输入一个表达式,比如1+1,它将打印该值。如果您在脚本中编写1+1,它将不会打印任何内容,这非常有意义。

但是,当您创建code.InteractiveInterpreter的子类,然后使用1+1方法将runcode传递给它时,它将不会打印2,这不太合理

有没有人知道干净方法让InteractiveInterpreter实例打印表达式的值?

注意:这需要非常强大,因为应用程序为用户提供了一个shell,我们都知道它们是什么样的。

干杯

P.S。这适用于Python3应用程序,但更好的Python2解决方案将获得检查。

1 个答案:

答案 0 :(得分:2)

不是code.InteractiveConsole的用途吗?

>>> 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

或使用嵌入式换行符:

>>> 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
>>>