Is it possible to make Python interpret a script l

2019-09-02 14:18发布

问题:

This question already has an answer here:

  • Simulate interactive python session 1 answer

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