How to import a file by its full path using C api?

PyObject * PyImport_ImportModule (const char * name)

How to specify the full path to the file and the name of the module?

how PyImport_SomeFunction(const char *path_to_script, const char *name)

Thanks Elias

+3
source share
6 answers

In the end, I ended up using load_source from the imp module:

s.sprintf( 
  "import imp\n" 
  "imp.load_source('%s', r'%s')", modname, script_path); 
PyRun_SimpleString(s.c_str()); 

I think this is the most acceptable solution. Other suggestions are welcome.

+1
source

Another solution for cases where the entire * .py file is in the same directory:

PySys_SetPath("path/with/python/files");
PyObject *pModule = PyImport_ImportModule("filename_without_extension");
+3
source

, , . Python imp, . load_module(), . Python/import.c; imp_load_module.

+2

, AlexP, . , . , sys.path. , API C , . Python ,

PyRun_SimpleString( "import sys\nsys.path.append(\"<insert folder path>\")\n" );

: (: )

PyObject* sys = PyImport_ImportModule( "sys" );
PyObject* sys_path = PyObject_GetAttrString( sys, "path" );
PyObject* folder_path = PyUnicode_FromString( "<insert folder path>" );
PyList_Append( sys_path, folder_path );

<insert folder path>/<file>.py

PyObject* mymodule = PyImport_ImportModule( "<file>" );

, "." .

+1

CPython imp , , .

++, modulePath moduleName - :

PyObject* loadModule(const char* modulePath, const char* moduleName)
{
    auto modules = PyImport_GetModuleDict();
    auto impModule = PyDict_GetItemString(modules, "imp");
    if (impModule)
    {
        // GetItemString returns a borrowed reference, but ImportModule
        // returns a new reference, so INCREF here to even it out
        Py_INCREF(impModule);
    }
    else
    {
        impModule = PyImport_ImportModule("imp");
        if (!impModule)
        {
            // we've tried hard enough, bail out
            PyErr_Print();
            return nullptr;
        }
    }

    // The Python API asks for non-const char pointers :(
    char methodName[] = "load_source";
    char args[] = "ss";
    auto module = PyObject_CallMethod(impModule, methodName, args, moduleName, modulePath);

    Py_XDECREF(impModule);
    Py_XDECREF(modulePath);
    return module;
}

" Python" , fancier refcount management, , .

+1

, stesim.

, , , .

path = "C:\\path\\to\\module\\module.py" // wrong
path = "C:/path/to/module/module.py"     // correct

Some other questions and answers (e.g. the path to Windows in python ) indicate that the first option should work too. I could not get it to work that way, no matter how I tried.

0
source

Source: https://habr.com/ru/post/1723884/


All Articles