简体   繁体   中英

Python C API - Reload a module

I use Python 3.4 and Visual 2010. I'm embedding Python using the C API to give the user some script capabilities in processing his data. I call python functions defined by the user from my C++ code. I call specific function like Apply() for example that the user has to define in a Python file. Suppose the user has a file test.py where he has defined a function Apply() that process some data. All I have to do is to import his module and get a "pointer" to his python function from the C++.

PySys_SetPath(file_info.absolutePath().toUtf8().data()));
m_module = PyImport_ImportModule(module_name.toUtf8().data());
if (m_module)
{
    m_apply_function = PyObject_GetAttrString(m_module, "Apply");
    m_main_dict = PyModule_GetDict(m_module);
}

So far, so good. But if the user modifies his script, the new version of his function is never taken into account. I have to reboot my program to make it work... I read somewhere that I need to reload the module and get new pointers on functions but the PyImport_ReloadModule returns NULL with "Import error".

// .... code ....
// Reload the module
m_module = PyImport_ReloadModule(m_module);

Any ideas ? Best regards, Poukill

The answer was found in the comments of my first post (thank you JF Sebastian), the PySys_SetPath has to contain also the PYTHONPATH. In my case, that is the reason why the PyImport_ReloadModule was failing.

QString sys_path = file_info.absolutePath() + ";" + "C:\\Python34\\Lib";
PySys_SetPath(UTF8ToWide(sys_path.toUtf8().data()));
m_module = PyImport_ReloadModule(m_module); // Ok !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM