Retrieving result from embedded execution

Chris Angelico rosuav at gmail.com
Thu May 10 22:48:26 EDT 2012


On Wed, May 9, 2012 at 5:07 AM, F L <mephisto_9000 at hotmail.com> wrote:
> Hello everyone,
>
> We are trying to implement our own interactive interpreter in our
> application
> using an embedded Python interpreter.
>
> I was wondering what would be the best way to retreive as text the result of
> executing Python code. The text must be exactly the same as it would be in
> the
> standalone interpreter.

Greetings!

The standalone interpreter - I assume you mean the interactive prompt?
It has slightly different handling of things (for instance, naked
expressions being written to standard output) from the more "usual"
invocation of the interpreter.

For your embedded Python, probably the easiest thing to do is to not
try to use interactive mode, but script mode:

PyObject* PyRun_String(const char *str, int start, PyObject *globals,
PyObject *locals)

Pass it a string of Python code and a dictionary to use for globals
and locals (they can be the same dict). Then when that finishes,
retrieve from that dictionary some predetermined name (eg "Output").
The Python code then needs simply to assign to Output and all will
work.

Another way to do it is to call a function inside the Python code, and
retrieve its return value.

> We are using python 2.7.
>
> Any suggestions?

Unless you have particular need to stick to the 2.x branch, I would
suggest moving to 3.3; many things are easier (especially Unicode).
But both work.

> Also, I'm new to mailling lists, what is the proper way to reply to someone?
> Should I
> reply directly to someone's email adress or is there a way to answer trough
> the server.

The usual convention is to reply on-list, unless it's particularly
private. Many mail clients will handle this conveniently; otherwise,
just manually replace the To address with the list address. As long as
you use reply (rather than starting a fresh email), all posts will be
correctly threaded both on the list and on the synchronized newsgroup
(comp.lang.python).

Chris Angelico



More information about the Python-list mailing list