模拟交互式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横幅):
>>> #
... # this is a python script
... #
... def foo(x,y):
... return x+y
...
>>> a=1
>>> b=2
>>>
>>> c=foo(a,b)
>>>
>>> c
3
>>>
我尝试将stdin喂入python,twitter的建议是“
bash脚本”,没有详细信息(在bash中使用script命令播放,没有乐趣)。我觉得应该很容易,但我缺少一些简单的东西。我需要使用exec
或编写解析器吗?
Python或ipython解决方案就可以了。然后,我可能想转换为html并在网络浏览器中突出显示语法,但这是另一个问题…。
-
我认为
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
并使其在python 2和3下运行。)