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

lipingffeng at lipingffeng at
Thu Apr 3 19:52:31 EDT 2008

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

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[i] = 48 + i;

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

    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);

    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.



More information about the Python-list mailing list