Help with use of code.InteractiveInterpreter for multiline code

Jim Sizelove sizelji at insightbb.com
Fri Dec 3 12:06:31 EST 2004


rick_muller at yahoo.com wrote:
> I'm trying to embed a Python interpreter in a GUI I'm developing, and
> I'm having trouble understanding the proper use of
> code.InteractiveInterpreter.
> 
[examples of calling the interpreter instance]
> What's the proper way to call the interpreter instance for a multiline
> example like this?
> 
> Thanks in advance,
> 
> Rick
> 

I haven't worked with the code module before, but here is my go at it. 
It seems that the call to runsource() needs the entire multiline code at 
once, with newlines including a trailing newline:

     >>> import code
     >>> a = code.InteractiveInterpreter()
     >>> a.runsource('def q():\n    print "hi, a"\n')
     False
     >>> a.runsource('q()')
     hi, a
     False

With the InteractiveConsole, you can push each line of code 
individually, like so:

     >>> import code
     >>> b = code.InteractiveConsole()
     >>> b.push('def q():')
     True
     >>> b.push('    print "hi, b"')
     True
     >>> b.push('')
     False
     >>> b.runsource('q()')
     hi, b
     False

HTH,
Jim



More information about the Python-list mailing list