2014-05-22 195 views
5

如何使用来自文件的输入来模拟python交互式会话并保存会话记录?换句话说,如果我有一个文件sample.py模拟交互式Python会话

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

a=1 
b=2 

c=foo(a,b) 

c 

我想sample.py.out,看起来像这样(略蟒蛇旗):

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

我试着喂标准输入到Python,Twitter的建议是'bash脚本',没有任何细节(在bash中使用脚本命令播放,没有喜悦)。我觉得它应该很容易,而我错过了一些简单的东西。我需要使用exec还是别的什么来编写解析器?

Python或ipython解决方案将会很好。我可能再要转换的Web浏览器的HTML和语法高亮这一点,但这是另一个问题....

+0

你是不是想你的交互式Python外壳的会话​​保存到文件或模拟蟒蛇壳/控制台运行? –

+0

@詹姆斯米尔我认为OP想要完全相反,一个脚本被转换为从交互式shell看起来像。 – luk32

+0

http://pythonhosted.org/sphinxcontrib-programoutput/ < - 这将做类似的事情。 –

回答

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()) 

(我更新使用代码fileinput,使其无论从stdinsys.argv读取,并使其在Python 2和3)

+2

它在锡上说什么。我有麻烦打破它:) – Spacedman

+0

我该如何使用它?它是来自python解释器还是bash?我输入>>> show(sample.py) – Tim

+0

也是,这个工作在Python3中吗? – Tim