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....
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With