How to obtain a 'interactive session' of a script?

jepler at unpythonic.net jepler at unpythonic.net
Sun Sep 18 11:28:36 EDT 2005


The 'code' module contains 'Utilities needed to emulate Python's interactive
interpreter.'.  By subclassing code.InteractiveConsole and replacing the
raw_input method with one which reads from a file, I think you can get what you
want.

The example below the classes uses StringIO so that it can be self-contained,
but you'll probably use a regular file instead.

import code, sys

class BoPeng(code.InteractiveConsole):
    def __init__(self, locals=None, filename="<console>", file = None):
        self.file = file or open(filename)
        code.InteractiveConsole.__init__(self, locals, filename)

    def raw_input(self, prompt):
        l = self.file.readline()
        if l == '': raise EOFError
        sys.stdout.write(prompt + l)
        return l.strip("\n")

session = '''\
print 3+3
for i in range(10):
    print i

print "Example of a traceback:"
1/0
'''

import StringIO
b = BoPeng(file = StringIO.StringIO(session))
b.interact(None)
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20050918/61ddd64a/attachment.sig>


More information about the Python-list mailing list