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

Fredrik Lundh fredrik at pythonware.com
Sun Sep 18 11:24:00 EDT 2005


Bo Peng wrote:

> I have a long list of commands in the form of a script and would like to
>  obtain a log file as if I enter the commands one by one. (The output
> will be used in a tutorial.) What would be the best way to do it? Copy
> and paste is not acceptable since I make frequent changes tot he script.

the first example on this page

    http://effbot.org/librarybook/code.htm

shows how to execute Python code line by line.

here's a variation that echoes the script fragments with the right prompts
in front of them:

import code

SCRIPT = [line.rstrip() for line in open("myscript.py")]

script = ""
prompt = ">>>"

for line in SCRIPT:
    print prompt, line
    script = script + line + "\n"
    co = code.compile_command(script, "<stdin>", "exec")
    if co:
        # got a complete statement.  execute it!
        exec co
        script = ""
        prompt = ">>>"
    else:
        prompt = "..."

</F> 






More information about the Python-list mailing list