Hi, I’m trying to use python embedded and I have a case where Py_InitializeFromConfig fails because the user directory is corrupted. In this case I restore the folder, check the hashes to make sure everything is ok and then call Py_InitializeFromConfig again but I’m still getting the same errors. If I just close and reopen the application the error is gone. I made sure I called PyConfig_Clear(&config); and PyErr_Clear(); before trying again but I’m still getting the error. Any ideas? Thanks!
My code:
if (PyImport_AppendInittab("MyCustomModule", PyInit_MyCustomModule) < 0) {
throwException("Failed to initialize python stdout redirector.");
}
const fs::path homePath = getPythonEnvironmentDir();
const std::wstring homeStringW(homePath.wstring());
const fs::path executablePath = getPythonExecutablePath();
const std::wstring executableStringW(executablePath.wstring());
PyPreConfig preConfig;
PyPreConfig_InitIsolatedConfig(&preConfig);
auto status = Py_PreInitialize(&preConfig);
if (PyStatus_Exception(status)) {
throwException("Failed to pre-initialize Python: {}", status.err_msg);
}
PyConfig config;
PyConfig_InitIsolatedConfig(&config);
status = PyConfig_SetString(&config, &config.home, homeStringW.data());
if (PyStatus_Exception(status)) {
PyConfig_Clear(&config);
PyErr_Clear();
throwException("Failed set Python home: {}", status.err_msg);
}
status = PyConfig_SetString(&config, &config.executable, executableStringW.data());
if (PyStatus_Exception(status)) {
PyConfig_Clear(&config);
PyErr_Clear();
throwException("Failed set Python executable: {}", status.err_msg);
}
status = Py_InitializeFromConfig(&config);
if (PyStatus_Exception(status)) {
PyConfig_Clear(&config);
PyErr_Clear();
throwException("Failed to initialize Python: {}", status.err_msg);
}
PyConfig_Clear(&config);
m_myCustomModule = PyImport_ImportModule("MyCustomModule");
if (m_myCustomModule == nullptr) {
PyErr_Clear();
throwException(DFF::Exception, "Failed to import MyCustomModule module.");
}
After I throw the exception on Py_InitializeFromConfig, I try/catch, fix the files and re-run this code.