emulating python shell

Fernando Perez fperez528 at yahoo.com
Tue Dec 28 18:18:03 EST 2004


Uwe Mayer wrote:

> Hi,
> 
> in an application I want to provide direct access to the python interpreter
> of the running program.
> I use rawinput() and exec() to read an input string and a self-made function
> to check wether the inputed block is closed and then execute it.
> 
> When running python interactively the result of the previous statement is
> assigned to the variable "_" and commands like dir() just output their
> results to stdout.
> However, executions of the sort:
> 
> exec("_ = "+command)
> 
> don't work.
> 
> Any ideas how to mimick python -i 's behaviour?

You can look at the code.py module in the python standard lib.  It implements a
pure-python interactive interpreter from scratch, so there's no need for you
to reinvent that particular wheel.  Since it's in the standard lib, you can
rely on it for deployment to external sites.

<plug>
If you want something more sophisticated, and ready-made for this kind of
embedding, look at ipython: http://ipython.scipy.org.  IPython is itself based
on code.InteractiveConsole, but at this point it has overridden almost all of
the  methods in the base class.

Embedding it is as easy as:

from IPython.Shell import IPShellEmbed 
ipshell = IPShellEmbed() 
ipshell() # this call anywhere in your program will start IPython 

You can have multiple embedded instances, and they can be initialized to use
anythingb

You can find further details about embedding ipython here:
http://ipython.scipy.org/doc/manual/node9.html

</plug>

HTH,

f




More information about the Python-list mailing list