Alex Martelli aleaxit at yahoo.com
Wed Jun 20 09:15:02 EDT 2001

"Mark Rowe" <mark21rowe at yahoo.com> wrote in message
news:3b305ce7 at news.actrix.gen.nz...
> Hey all,
> Just been fiddling round with embedding Python in a C program, and one
> has me stuck.  I would like the user to be able to enter some python code
> containing functions, then at a later point execute one of these functions
> by name.  I'm not really sure what i need to do for this to work

You don't have to do much.  Collect the source code that the user
enters (e.g. in a text-entry window in a GUI?), into one big Python
string (make sure there's a '\n' at the end:-), feed it to builtin
function compile() and make sure to catch a SyntaxError that will
be raised if the code has syntax errors, and let the user know.   If
there are no errors, compile() returns a code-object.  Stash it away,
and at any later time you can pass it to statement 'exec' (you may
want to pass specific dictionaries to control execution namespaces).
Again, be sure to catch and report any exceptions that may arise.

This is all at the Python-level, where it's easiest, but of course there
is equivalent functionality accessible from the C API, too -- it's just
more work (as usual for C vs Python:-) so, the more you can do in
Python, the merrier, no?-)


More information about the Python-list mailing list