模拟交互式python会话

Spa*_*man 5 python

如何使用文件输入模拟python交互式会话并保存成绩单?换句话说,如果我有一个文件sample.py:

#
# this is a python script
#
def foo(x,y):
   return x+y

a=1
b=2

c=foo(a,b)

c
Run Code Online (Sandbox Code Playgroud)

我希望sample.py.out看起来像这样(省略python横幅):

>>> #
... # this is a python script
... #
... def foo(x,y):
...    return x+y
... 
>>> a=1
>>> b=2
>>> 
>>> c=foo(a,b)
>>> 
>>> c
3
>>> 
Run Code Online (Sandbox Code Playgroud)

我已经尝试过stdin到python,twitter的建议是'bash script'没有细节(用bash中的脚本命令播放,没有欢乐).我觉得应该很容易,而且我错过了一些简单的东西.我是否需要使用exec或其他东西编写解析器?

Python或ipython解决方案没问题.然后我可能希望转换为HTML和语法在Web浏览器中突出显示,但这是另一个问题....

Kos*_*Kos 7

我认为code.interact会起作用:

from __future__ import print_function
import code
import fileinput


def show(input):
    lines = iter(input)

    def readline(prompt):
        try:
            command = next(lines).rstrip('\n')
        except StopIteration:
            raise EOFError()
        print(prompt, command, sep='')
        return command

    code.interact(readfunc=readline)


if __name__=="__main__":
    show(fileinput.input())
Run Code Online (Sandbox Code Playgroud)

(我更新了要使用的代码,fileinput以便从中读取stdinsys.argv使其在python 2和3下运行.)

  • 它在锡上说了什么.我在打破它时遇到了麻烦:) (2认同)