embedding interactive python interpreter

Eric Frederich eric.frederich at gmail.com
Wed Sep 11 14:12:46 EDT 2013


Scott,

Yes.
As Mark Hammond suggested I took a look into the code/console modules.
I wound up using InteractiveConsole from the code module.
I'm sure my requirements are completely different from yours but I'll
explain what I did anyway...

I was working with a client/server architecture where I wanted the client
to be able to interact with a server-side Python console.
Yes, I know this is a huge security hole.
It is only used as a debugging console to be able to interactively inspect
the state of the remote server process from within the client application
itself.

This 3rd party client server application I was customizing allows me to
write my own services.
So I wrote a service that accepts a string (the python line) and returns
two strings and a boolean (stdout, stderr, and whether or not the
interpreter expects more input).
That boolean basically controls whether the console should show a ">>>" or
a "..." and comes from InteractiveConsole.push.

To get stdout and stderr I monkey patched sys.stdout and sys.stderr with an
instance of MyBuffer.

class MyBuffer(object):
    def __init__(self):
        self.buffer = []
    def write(self, data):
        self.buffer.append(data)
    def get(self):
        ret = ''.join(self.buffer)
        self.buffer = []
        return ret

In my subclass of InteractiveConsole I defined the following...

    def __init__(self, *args, **kwargs):
        InteractiveConsole.__init__(self, *args, **kwargs)
        self.mb_out = MyBuffer()
        self.mb_err = MyBuffer()

    def process(self, s):
        sys.stdout, sys.stderr = self.mb_out, self.mb_err
        more = self.push(s)
        sys.stdout, sys.stderr = sys.__stdout__, sys.__stderr__
        return self.mb_out.get(), self.mb_err.get(), more

My service (written in c++), upon initialization gets a handle to a
singleton instance of this InteractiveConsole sublcass using the Python C
APIs.
When the service responds to a request it uses the Python C APIs to call
the process method above and returns the two strings and the boolean.

The client, which happens to be Java/Eclipse based, then has something that
resembles a Python console in the GUI and uses that single service to
interact with the remote Python console.

Lots of stuff going on but it works very well.



On Wed, Sep 11, 2013 at 1:42 PM, Scott <ihearthonduras at gmail.com> wrote:

> Eric,
>
> https://mail.python.org/pipermail/python-list/2011-March/600441.html
>
> Did you ever figure this out?  I'm trying to embed an interactive
> interpreter, and I'm sure that python has an easy way to do this, but I
> can't seem to find it...
>
> Thanks,
> -C. Scott! Brown
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130911/66cefb7e/attachment.html>


More information about the Python-list mailing list