mdefreitas at mdefreitas at
Mon May 1 01:15:31 CEST 2000

In article <8ehnvs$m0h$1 at>,
  Cedric Adjih <adjih at> wrote:
> mdefreitas at 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
> > 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
> > 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"
> > variable settings from it's caller. Is there a way to give each
> > python script a fresh, clean environment? The nested script should
> > effect the environment of it's caller either. Is that what the
> > and local dictionaries for the API function PyRun_File are for? If
> > 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
> 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

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
Before you buy.

More information about the Python-list mailing list