OGS
ogs_embedded_python.cpp
Go to the documentation of this file.
1
11#include "ogs_embedded_python.h"
12
13#include <pybind11/embed.h>
14
15#include <algorithm>
16
17#include "BaseLib/Logging.h"
21
23{
24 DBUG("Binding Python module OpenGeoSys.");
25
29
30 // Check for activated virtual environment and add it to sys.path
31 pybind11::exec(R"(
32 import os
33 import sys
34 if "VIRTUAL_ENV" in os.environ:
35 venv_site_packages_path = f"{os.environ['VIRTUAL_ENV']}/lib/python{sys.version_info.major}.{sys.version_info.minor}/site-packages"
36 if os.path.exists(venv_site_packages_path):
37 print(
38 f"Virtual environment detected, adding {venv_site_packages_path} to sys.path."
39 )
40 sys.path.insert(0, venv_site_packages_path)
41 )");
42}
43
44#ifndef OGS_BUILD_SHARED_LIBS
45
46// Hackish trick that hopefully ensures that the linker won't strip the symbol
47// pointed to by p from the library being built.
48template <typename T>
49void mark_used(T p)
50{
51 volatile T vp = p;
52 vp = vp;
53}
54
55#endif // OGS_BUILD_SHARED_LIBS
56
57namespace ApplicationsLib
58{
59pybind11::scoped_interpreter setupEmbeddedPython()
60{
61#ifndef OGS_BUILD_SHARED_LIBS
62 // pybind11_init_impl_OpenGeoSys is the function initializing the embedded
63 // OpenGeoSys Python module. The name is generated by pybind11. If it is not
64 // obvious that this symbol is actually used, the linker might remove it
65 // under certain circumstances.
66 mark_used(&pybind11_init_impl_OpenGeoSys);
67#endif
68
69 // Allows ogs to be interrupted by SIGINT, which otherwise is handled by
70 // python. See
71 // https://docs.python.org/3/c-api/exceptions.html#c.PyErr_CheckSignals and
72 // https://pybind11.readthedocs.io/en/stable/faq.html#how-can-i-properly-handle-ctrl-c-in-long-running-functions
73 constexpr bool init_signal_handlers = false;
74 return pybind11::scoped_interpreter{init_signal_handlers};
75}
76
77} // namespace ApplicationsLib
void DBUG(fmt::format_string< Args... > fmt, Args &&... args)
Definition Logging.h:30
pybind11::scoped_interpreter setupEmbeddedPython()
void pythonBindSourceTerm(pybind11::module &m)
Creates Python bindings for the Python source term class.
void pythonBindBoundaryCondition(pybind11::module &m)
Creates Python bindings for the Python BC class.
void bheInflowpythonBindBoundaryCondition(pybind11::module &m)
Creates BHE Inflow Python bindings for the Python BC class.
void mark_used(T p)
PYBIND11_EMBEDDED_MODULE(OpenGeoSys, m)