Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 833
poukill Avatar asked Dec 09 '25 05:12

poukill


1 Answers

The answer was found in the comments of my first post (thank you J.F 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 !
like image 132
poukill Avatar answered Dec 11 '25 19:12

poukill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!