当您使用
Python Interactive Interpreter时,您可以输入一个表达式,例如1 1,它将打印该值.如果你在脚本中写1 1,它将不会打印任何东西,这是完全合理的.
但是,当您创建code.InteractiveInterpreter的子类,然后使用runcode方法将1 1传递给它时,它将不会打印2,这没有多大意义.
有没有人知道一个干净的方法来使InteractiveInterpreter实例打印表达式的值?
注意:这需要非常强大,因为应用程序为用户提供了一个shell,我们都知道它们是什么样的.
干杯
附:这是一个Python3应用程序,但更好的Python2解决方案将得到检查.
最佳答案 这不是
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
>>>