DynExp
Highly flexible laboratory automation for dynamically changing experiments.
PyUtil.cpp
Go to the documentation of this file.
1 // This file is part of DynExp.
2 
3 #include "stdafx.h"
4 #include "PyUtil.h"
5 
9 PYBIND11_EMBEDDED_MODULE(PyModuleStdoutLogger, m)
10 {
11  py::class_<Util::PyStdoutLoggerWrapper>(m, "StdoutLoggerWrapper")
13  .def("flush", &Util::PyStdoutLoggerWrapper::flush);
14 }
15 
16 namespace Util
17 {
18  void PyStdoutLoggerWrapper::write(std::string Str)
19  {
20  std::erase(Str, '\r');
21  std::replace(Str.begin(), Str.end(), '\n', ' ');
22 
23  if (!Str.empty() && Str.find_first_not_of(" ") != std::string::npos)
24  Util::EventLog().Log("[Py] \"" + Str + "\"");
25  }
26 
28  {
29  py::gil_scoped_acquire acquire;
30 
31  // Redirect Python's stdout.
32  py::module_::import("PyModuleStdoutLogger");
33  Module_sys = py::module_::import("sys");
34  Module_sys.attr("stdout") = Logger;
35 
36 #ifdef DYNEXP_UNIX
37  // Add folder 'lib-dynload' to path and use release modules. Otherwise, Python does not find basic modules.
38  py::exec(R"(
39  new_path = []
40  for p in sys.path:
41  p = p.replace('debug/', '')
42  new_path.append(p)
43  if '/vendor/vcpkg/installed/' in p and '/site-packages' in p:
44  p = p.replace('site-packages', 'lib-dynload')
45  new_path.append(p)
46  sys.path = new_path
47  )");
48 #endif // DYNEXP_UNIX
49  }
50 
52  {
53  py::gil_scoped_acquire acquire;
54 
55  py::print("Importing Python modules from");
56  py::print(Module_sys.attr("path"));
57  }
58 }
PYBIND11_EMBEDDED_MODULE(PyModuleStdoutLogger, m)
Definition: PyUtil.cpp:9
Provides utilities related to pybind11 within DynExp's Util namespace.
void Log(const std::string &Message, const ErrorType Type=ErrorType::Info, const size_t Line=0, const std::string &Function="", const std::string &File="", const int ErrorCode=0, const std::stacktrace &Trace={}) noexcept
Logs an event from information specified manually.
Definition: Util.cpp:309
py::module_ Module_sys
Handle to the Python sys module.
Definition: PyUtil.h:53
void PrintDebugInfo()
Writes information on the Python interpreter configuration to DynExp's log.
Definition: PyUtil.cpp:51
PyStdoutLoggerWrapper Logger
Wrapper to forward DynExp's event log to Python.
Definition: PyUtil.h:51
void write(std::string Str)
Formats the string passed to the function and writes it to the event log.
Definition: PyUtil.cpp:18
void flush()
Required, but does nothing.
Definition: PyUtil.h:36
DynExp's Util namespace contains commonly used functions and templates as well as extensions to Qt an...
Definition: circularbuf.cpp:7
EventLogger & EventLog()
This function holds a static EventLogger instance and returns a reference to it. DynExp uses only one...
Definition: Util.cpp:509
Accumulates include statements to provide a precompiled header.