Embedding Python question

Martin von Loewis loewis at informatik.hu-berlin.de
Wed Jan 12 15:49:23 EST 2000


"David Max" <max at neomeo.com> writes:

> However, if I use PyRun_String(...) instead and pass an appropriate pointer
> for the globals, then it works.

Instead of doing PyRun things, you are better off using more direct
functions, instead of going through the source code level. I.e. use
things like PyObject_CallFunction to invoke a function, and
PyObject_Print to perform the equivalent of print.

> This works, but I'm not sure that I understand what I'm doing. For
> example, I am leaving the locals as NULL. What should go there?

The PyRun_String is the equivalent of a Python "exec" statement. Just
as you pass a globals and a locals dictionary to exec, you do the same
here. One difference is assignments: Assignments go into the local
dictionary, unless the variable is marked global in the code you are
executing.

> And how would I get a handle to it? 

You don't need to:

>>> g={}
>>> l={}
>>> exec "a=5" in g,l
>>> g.keys()
['__builtins__']
>>> l.keys()
['a']

So you can start with fresh dictionaries (e.g. from PyDict_New), and
use those to keep state across different expressions.

> What does it mean to use Py_file_input as the start tag as opposed
> to using Py_single_input or Py_eval_input?

This is the same as the third argument to the compile function:

>>> print compile.__doc__
compile(source, filename, mode) -> code object

Compile the source string (a Python module, statement or expression)
into a code object that can be executed by the exec statement or eval().
The filename will be used for run-time error messages.
The mode must be 'exec' to compile a module, 'single' to compile a
single (interactive) statement, or 'eval' to compile an expression.

> Also, I have tried to replace the call to execute the string "import os"
> with a call to one of the PyImport functions. Nothing I've hit on so far
> seems to work, and I'm not sure that I can tell the difference between some
> of the functions like PyImport_ImportModuleEx, PyImport_Import and
> PyImport_AddModule. If anybody can help me figure out which call I should
> use, I would be appreciative.

See
http://www.python.org/doc/current/api/importing.html. 

PyImport_ImportModule is probably most convenient; you pass the module
name, and it gives you a module reference. Don't drop this reference -
you need it to access the module's dictionary.

Regards,
Martin



More information about the Python-list mailing list