How to obtain a 'interactive session' of a script?
Fredrik Lundh
fredrik at pythonware.com
Sun Sep 18 12:50:13 EDT 2005
Bo Peng wrote:
>> 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 = "..."
>
> This one fails at function definition.
>
> def fun():
> a=1
> b=2 <--- not included.
hmm. looks like a bug in compile_command. stripping off the trailing
newline seems to fix it:
co = code.compile_command(script[:-1], "<stdin>", "exec")
(to make things look right, you need to add an empty line after each
function definition in your code)
</F>
More information about the Python-list
mailing list