Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate interactive python session

Tags:

python

How can I simulate a python interactive session using input from a file and save what would be a transcript? In other words, if I have a file sample.py:

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

a=1
b=2

c=foo(a,b)

c

I want to get sample.py.out that looks like this (python banner omitted):

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

I've tried feeding stdin to python, twitter's suggestions were 'bash script' with no details (played with the script command in bash, no joy). I feel it should be easy, and I'm missing something simple. Do I need to write a parser using exec or something?

Python or ipython solutions would be fine. And I might then want to convert to html and syntax highlight this in a web browser, but that's another problem....

like image 941
Spacedman Avatar asked May 22 '14 14:05

Spacedman


1 Answers

I think code.interact would work:

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

(I updated the code to use fileinput so that it reads from either stdin or sys.argv and made it run under python 2 and 3.)

like image 180
Kos Avatar answered Oct 02 '22 06:10

Kos