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