Q: Recursive embedded Python interpreters?

mdefreitas at sikorsky.com mdefreitas at sikorsky.com
Thu Apr 27 14:19:22 EDT 2000


I am working on a helicopter simulation user-interface that takes
commands such as:

> start_sim
> freeze_sim
> altitude = 100.0
> end_sim

I would like to add scripting capabilities to this user-interface, so I
am attempting to extend and embed Python. I am adding a new command
(python) to my user interface that will run a python script with
optional arguments:

> python  script.py  arg1  arg2

My first step was to extend python with a module “ui” that python
scripts can import to execute various user interface commands. This was
fairly easy. I am now trying to embed the python interpreter into my
user interface. I anticipate a possible problem when a python scripts
executes the “ui” command to run another python script. I anticipate re-
entry issues. I assume I have to create a new interpreter for each
nested call to the python interpreter. I really don’t understand the
mechanics of how this works, but from comp.lang.python archives, and
from the Demos/pysvr example that came bundled with the python1.5
distribution this is what I think I have to do:

static int nest_level = 0;
static PyThreadState *gtstate = 0;

void interp(char *script) {
   if (nest_level == 0) {
      nest_level++;  // init topmost interp
      Py_Initialize();
      PyEval_InitThreads();
      gtstate = PyEval_SaveThread();
   } else {
      PyEval_ReleaseLock();  // nested interp needs to relinquish lock?
   }

   PyEval_AcquireLock();
   PyThreadState *tstate = Py_NewInterpreter();
   FILE *fd = fopen(script, “r”);
   PyRun_SimpleFile(fd, script);
   Py_EndInterpreter(tstate);
   PyEval_ReleaseLock();
   nest_level--;
   if (nest_level == 0) {
      PyEval_AcquireThread(gtstate); // top-most interp... clean up
      gtstate = 0;
      Py_Finalize();
   } else {
      PyEval_AcquireLock();  // need to reacquire lock if nested?
   }
}

Is this right? Did I miss anything? Also… how do I pass arguments to
the (possibly nested) scripts.

Thanks in advance for any help.





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



More information about the Python-list mailing list