MORE INFO

mdefreitas at sikorsky.com mdefreitas at sikorsky.com
Mon May 1 01:15:31 CEST 2000


In article <8ehnvs$m0h$1 at ites.inria.fr>,
  Cedric Adjih <adjih at crepuscule.com> wrote:
> mdefreitas at sikorsky.com wrote:
>
> >> Do you want to run several python scripts (and several ui.commands
> >> C code) concurently (how would you synchronize?) ?
>
> > I do not want to run concurrently, I just want to run in one thread
of
> > execution, but recursively.
>
> Ok.
>
> >> Note that if all you want is to have C code that calls Python
> >> code that calls C code (through a module) that calls Python code
> >> without threads, PyRun_XXX functions are re-entrant.
>
> > Thanks! That's what I needed to know. I now modified (and
simplified)
> > my code as follows:
>
> > void interp(char *script) {
> >    static int nest_level = 0;
> >    FILE *fd = fopen(script, "r");
> >    if (nest_level == 0) {
> >       Py_Initialize();
> >       PyRun_SimpleString("import ui\n"); // import my ui
> >    }
> >    nest_level++;
> >    PyRun_SimpleFile(fd, script);
> >    nest_level--;
> >    if (nest_level == 0) Py_Finalize();
> > }
>
> > The only problem is that the nested script that is run "remembers"
the
> > variable settings from it's caller. Is there a way to give each
nested
> > python script a fresh, clean environment? The nested script should
not
> > effect the environment of it's caller either. Is that what the
global
> > and local dictionaries for the API function PyRun_File are for? If
so,
> > is there any examples on their usage. The C/API doc isn't all that
> > explicit.
>
>   Indeed.
>   PyRun_File is actually implementing most of the "execfile(...)"
> code (see http://www.python.org/doc/current/lib/built-in-funcs.html).
> Python source code for execfile is also an example of use for
> PyRun_File.
>   Passing empty dictionaries would be a way to have a "clean"
> environment except if a script imports a Python module and fiddles
> with its internals. Because modules will be shared among scripts.
> But fiddling with internals is very bad style.
>
> -- Cedric

Hmmm... I looked at the source code for execfile and it looks like it
either passes PyRun_File the dictionaries that were passed into
execfile itself, or if none was passed in, it passed PyRun_File the
current dictionaries as default. I believe that what I need to do is
pass in EMPTY dictionaries for the globals and locals. I tried the
following:

PyRun_File(fd, script, Py_file_input, PyDict_New(), PyDict_New());

But that didn't seem to work. The top level script seemed OK, but the
nested one didn't seem to execute. Is there something else that needs
to be done? Is it bad to pass in an empty global dictionary? Also, I
noticed that there was a PyDict_New function, but not a PyDict_Delete
function... I assume memory cleanup is automatic?

As always, thanks for the help...


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list