模拟交互式python会话

模拟交互式python会话,python,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 我想得到如下的sample.py.out(python横幅省略): 我曾尝试将stdin输入python,twitter的建议是“bash脚本”,没有任何细节(在bash中使用script命令,没有乐趣)。我觉得这应该很容易,

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

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

a=1
b=2

c=foo(a,b)

c
我想得到如下的
sample.py.out
(python横幅省略):

我曾尝试将stdin输入python,twitter的建议是“bash脚本”,没有任何细节(在bash中使用script命令,没有乐趣)。我觉得这应该很容易,我错过了一些简单的事情。我是否需要使用
exec
或其他方法编写解析器


Python或ipython解决方案可以。然后我可能想转换成html并在web浏览器中突出显示语法,但这是另一个问题….

我认为
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())

(我将代码更新为使用
fileinput
,以便它从
stdin
sys.argv
读取,并使其在Python2和3下运行。)

您是想将交互式Pythonshell的会话保存到文件还是模拟Pythonshell/控制台?@JamesMills我认为OP想要的正好相反,要转换为类似于交互式shell的脚本。是的,稍微澄清一下。从文件中获取输入,使其看起来像是键入的。在我的示例中,我实际上将n paste剪切到了运行的python中。@JamesMills,你确定吗?据我所知,该扩展只运行一个外部命令,并将完整的输出(STDOUT)插入到文档中。我不知道这将如何工作,以模拟一个交互式解释器逐行读取和评估源代码。按照tin上的说明执行。我打破它有困难:)我怎么用这个?它是来自python解释器还是bash?我是否输入>>>show(sample.py)@Tim将代码另存为
interact.py
并将输入另存为
sample.py
,然后执行
python interact.py sample.py
。当您使用
打印的新语法时,它将在py3中工作。
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())