Skip to content

Commit

Permalink
Set PYTHONHOME when embedding Python on Windows
Browse files Browse the repository at this point in the history
Without this, the default Python path is not populated correctly,
and is based on the path to the user's executable instead.
  • Loading branch information
speth committed Sep 11, 2022
1 parent 330f08b commit 2462fab
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 0 deletions.
1 change: 1 addition & 0 deletions site_scons/buildutils.py
Expand Up @@ -1297,6 +1297,7 @@ def setup_python_env(env):
env["py_version_nodot"] = py_version_nodot
env["py_version_short"] = info["py_version_short"]
env["py_plat"] = plat
env["py_base"] = info["installed_base"]
env["site_packages"] = info["site_packages"]
env["user_site_packages"] = info["user_site_packages"]
if env["OS"] != "Windows":
Expand Down
3 changes: 3 additions & 0 deletions src/SConscript
Expand Up @@ -87,6 +87,9 @@ if env["python_package"] == "full":
localenv.Depends(cythonized, pxd)

obj = pyenv.SharedObject(cythonized[0])
if env["OS"] == "Windows":
escaped_home = '\\"' + pyenv["py_base"].replace("\\", "\\\\") + '\\"'
pyenv.Append(CPPDEFINES={"CT_PYTHONHOME": escaped_home})
env.Command('#src/extensions/pythonExtensions.h', '#build/src/extensions/pythonExtensions.h',
Copy('$TARGET', '$SOURCE'))
libraryTargets.append(obj)
Expand Down
12 changes: 12 additions & 0 deletions src/extensions/PythonExtensionManager.cpp
Expand Up @@ -11,6 +11,10 @@

#include <boost/algorithm/string.hpp>

#ifdef _WIN32
#include <windows.h>
#endif

namespace ba = boost::algorithm;
using namespace std;

Expand Down Expand Up @@ -66,6 +70,14 @@ namespace Cantera
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
Py_Initialize();
}

Expand Down

0 comments on commit 2462fab

Please sign in to comment.