Is it possible to make Python interpret a script line by line and generate output as if from an interactive shell? [duplicate]

拟墨画扇 提交于 2019-12-25 05:56:34

问题


Considering the following interactive shell session.

Python 2.7.5+ (default, Feb 27 2014, 19:37:08) 
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 1+1
2
>>> 2+5
7
>>> "foo"
'foo'
>>> 

Observe how, after every line, the interpreter will echo the result to the console.

If I put those same three commands into a script Foo.py without print statements, there will be no output generated.

Is there a way to force the Python interpreter to generate the same output as it would under interactive mode without modifying the code to manually insert print statements?


回答1:


import code
console = code.InteractiveConsole()
prompt = '>>>'
source = '''
1 + 1
2+5
"foo"
x = 1
x
y = (2+
     3)
y + x     
'''.splitlines()
for line in source:
    print('{p} {l}'.format(p=prompt, l=line.rstrip()))
    prompt = '...' if console.push(line) else '>>>'

yields

>>> 
>>> 1 + 1
2
>>> 2+5
7
>>> "foo"
'foo'
>>> x = 1
>>> x
1
>>> y = (2+
...      3)
>>> y + x
6


来源:https://stackoverflow.com/questions/25088718/is-it-possible-to-make-python-interpret-a-script-line-by-line-and-generate-outpu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!