模拟交互式python会话

发布于 2021-01-29 14:56:36

如何 使用文件输入 模拟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并在网络浏览器中突出显示语法,但这是另一个问题…。

关注者
0
被浏览
89
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    我认为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下运行。)



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看