how to do "load script; run script" in a loop in embedded python?

L

lipingffeng

Hi, all,

I am currently involved in a project that needs to load/run a python
script dynamically in a C application. The sample code is as
following:

PyObject *LoadScript(char *file, char *func)
{
PyObject *pName, *pModule, *pDict, *pFunc;

pName = PyString_FromString(file);
pModule = PyImport_Import(pName);
pDict = PyModule_GetDict(pModule);
pFunc = PyDict_GetItemString(pDict, func);
return pFunc;
}

int RunScript(PyObject *pFunc, PyObject *arglist)
{
PyObject *pValue = PyObject_CallFunction(pFunc, "O", arglist);
int ret = PyInt_AsLong(pValue);
return ret;
}

int main(int argc, char *argv[])
{
PyObject *arglist, *pFunc;
char imgData[10];
int ret;

for(int i = 0; i < 10; i++)
imgData = 48 + i;

arglist = Py_BuildValue("s#", imgData, 10);

Py_SetProgramName(argv[0]);
Py_Initialize();
PySys_SetArgv(argc, argv);

for (int k = 0; k < 3; k++) // using loop to imitate dynamic
loading/running script
{
pFunc = LoadScript(argv[1], argv[2]);
ret = RunScript(pFunc, arglist);
}

Py_Finalize();
return 0;
}

The first loop is perfectly ok, but on the second loop, script loading
is successful but running will always fail.

Any ideas would be highly apprecicated.

Thanks,

Liping
 
G

Gabriel Genellina

Hi, all,

I am currently involved in a project that needs to load/run a python
script dynamically in a C application. The sample code is as
following:

PyObject *LoadScript(char *file, char *func)
{
PyObject *pName, *pModule, *pDict, *pFunc;

pName = PyString_FromString(file);
pModule = PyImport_Import(pName);
pDict = PyModule_GetDict(pModule);
pFunc = PyDict_GetItemString(pDict, func);
return pFunc;
}

Remember to check all PyObject* return values, NULL means there was an
error.
And pay attention to reference counts! Read the section about reference
counts in both books, Extending and Embedding, and the Python API
Reference. http://docs.python.org/
The first loop is perfectly ok, but on the second loop, script loading
is successful but running will always fail.

"fail" in what form? A Python exception? The program freezes? A core dump?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top