Embedded Python 2.7.2 Importing a module from a user-defined directory

前端 未结 1 1217
暖寄归人
暖寄归人 2021-01-05 03:59

I\'m embedding Python into a C/C++ application that will have a defined API.

The application needs to instantiate classes defined in a script, which are structured r

相关标签:
1条回答
  • 2021-01-05 04:42

    you need to specify userscript and not userscript.py also use PyImport_ImportModule it directly takes a char *

    userscript.py means module py in package userscript

    this code works for me:

    #include <stdio.h>
    #include <stdlib.h>
    #include <Python.h>
    
    int main(void)
    {
        const char *scriptDirectoryName = "/tmp";
        Py_Initialize();
        PyObject *sysPath = PySys_GetObject("path");
        PyObject *path = PyString_FromString(scriptDirectoryName);
        int result = PyList_Insert(sysPath, 0, path);
        PyObject *pModule = PyImport_ImportModule("userscript");
        if (PyErr_Occurred())
            PyErr_Print();
        printf("%p\n", pModule);
        Py_Finalize();
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题