Embedding python and multiple separate scripts

Stefan D stefan at damp.homeip.net
Fri Apr 14 10:23:52 EDT 2006


Hi,

I'm trying to embed python into an chat bot I've made in c++. After 
googling around and reading docs for almost a day I have a few 
questions. First of all it seems like the best way to be able to run 
separate scripts in different, isolated environments is to create a 
sub-interpreter (by using Py_NewInterprete()) with an associated thread 
for each script/file. Or is this wrong?

The big problem I have is when I want to call a python function. When 
loading a script I use the following code:
 PyEval_AcquireLock(); // get global lock so we can create a new interpreter
 threadState = Py_NewInterpreter(); // create a new sub-interpreter and 
get a pointer to the first thread
 PyThreadState_Swap(threadState); // switch to our new thread state
 appModule = PyImport_AddModule("hostapp"); // create a module for this 
program
 PyModule_AddIntConstant(appModule, "SEVENTEEN", 17); // set a test constant
 FILE* fp = fopen(filename, "r"); // load the python script file
 PyRun_SimpleFile(fp, filename);
 fclose(fp);
 PyEval_ReleaseThread(threadState); // set current thread state to NULL 
and release global lock

When loading a script that contains:
 import hostapp
 print "test: ",hostapp.SEVENTEEN

it prints out "test: 17" nicely after the call to PyRun_SimpleFile(...). 
So far so good, but the problem starts when I try to call a python 
function from c++. Here's the code that isn't working:
 PyEval_AcquireThread(threadState);
 PyObject* func = PyDict_GetItemString(PyImport_GetModuleDict(), 
"testfunc");
 if(PyCallable_Check(func)) {
   // never get this far
 }
 PyEval_ReleaseThread(threadState);

PyDict_GetItemString always return NULL for me, although I've defined 
the function as:
 def testfunc():
   print "hi there"

in the python file. Running PyRun_SimpleString("testfunc()\n") just 
after  PyEval_AcquireThread() works like a charm though. Any ideas? I 
kinda get the feeling that I don't get the dict from 
PyImport_GetModuleDict() that I'm expecting.

Thanks in advance..
/Stefan




More information about the Python-list mailing list