Skip to content

Commit

Permalink
Make Python extensions compatible with venv
Browse files Browse the repository at this point in the history
  • Loading branch information
speth committed Sep 11, 2022
1 parent 7ace1bc commit 5e15f57
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 8 deletions.
3 changes: 3 additions & 0 deletions include/cantera/extensions/PythonExtensionManager.h
Expand Up @@ -31,6 +31,9 @@ class PythonExtensionManager : public ExtensionManager
//! Function called from Cython to register an ExtensibleRate implementation
static void registerPythonRateBuilder(const std::string& moduleName,
const std::string& className, const std::string& rateName);

private:
static bool s_imported;
};

}
Expand Down
38 changes: 30 additions & 8 deletions src/extensions/PythonExtensionManager.cpp
Expand Up @@ -10,6 +10,7 @@
#include "pythonExtensions.h" // generated by Cython

#include <boost/algorithm/string.hpp>
#include <codecvt>

#ifdef _WIN32
#include <windows.h>
Expand Down Expand Up @@ -67,20 +68,40 @@ std::string getPythonExceptionInfo()
namespace Cantera
{

bool PythonExtensionManager::s_imported = false;

PythonExtensionManager::PythonExtensionManager()
{
if (!Py_IsInitialized()) {
#if defined(CT_PYTHONHOME) && defined(_WIN32)
const char* old_pythonhome = getenv("PYTHONHOME");
if (old_pythonhome == nullptr || old_pythonhome[0] == '\0') {
std::string pythonhome = "PYTHONHOME=";
pythonhome += CT_PYTHONHOME;
_putenv(pythonhome.c_str());
}
#endif
// Update the path to include the virtual environment, if one is active
const char* venv_path = getenv("VIRTUAL_ENV");
if (venv_path != nullptr) {
#ifdef _WIN32
string suffix = "\\Scripts\\python.exe";
#else
string suffix = "/bin/python";
#endif
string path(venv_path);
path += suffix;
wstring wpath = wstring_convert<codecvt_utf8<wchar_t>>().from_bytes(path);
Py_SetProgramName(wpath.c_str());
} else {
#if defined(CT_PYTHONHOME) && defined(_WIN32)
const char* old_pythonhome = getenv("PYTHONHOME");
if (old_pythonhome == nullptr || old_pythonhome[0] == '\0') {
string pythonhome = "PYTHONHOME=";
pythonhome += CT_PYTHONHOME;
_putenv(pythonhome.c_str());
}
#endif
}
Py_Initialize();
}

if (s_imported) {
return;
}

// PEP 489 Multi-phase initialization

// The 'pythonExtensions' Cython module defines some functions that are used
Expand Down Expand Up @@ -130,6 +151,7 @@ PythonExtensionManager::PythonExtensionManager()
}
Py_DECREF(spec);
Py_DECREF(pyModule);
s_imported = true;
}

void PythonExtensionManager::registerRateBuilders(const string& extensionName)
Expand Down

0 comments on commit 5e15f57

Please sign in to comment.