CMS 3D CMS Logo

PyBind11ProcessDesc.cc
Go to the documentation of this file.
6 #include <pybind11/embed.h>
7 #include <pybind11/pybind11.h>
8 
9 #include <sstream>
10 #include <iostream>
11 
12 namespace cmspython3 {
13  PyBind11ProcessDesc::PyBind11ProcessDesc() : theProcessPSet(), theMainModule(), theOwnsInterpreter(false) {}
14 
17  pybind11::initialize_interpreter();
19  prepareToRead();
20  read(config);
21  }
22 
24  : theProcessPSet(),
25  theMainModule(),
27 
28  {
29  pybind11::initialize_interpreter();
31  prepareToRead();
32  {
33 #if PY_MAJOR_VERSION >= 3
34  typedef std::unique_ptr<wchar_t[], decltype(&PyMem_RawFree)> WArgUPtr;
35  std::vector<WArgUPtr> v_argv;
36  std::vector<wchar_t*> vp_argv;
37  v_argv.reserve(argc);
38  vp_argv.reserve(argc);
39  for (int i = 0; i < argc; i++) {
40  v_argv.emplace_back(Py_DecodeLocale(argv[i], nullptr), &PyMem_RawFree);
41  vp_argv.emplace_back(v_argv.back().get());
42  }
43 
44  wchar_t** argvt = vp_argv.data();
45 #else
46  char** argvt = argv;
47 #endif
48 
49  PySys_SetArgv(argc, argvt);
50  }
51  read(config);
52  }
53 
55  if (theOwnsInterpreter) {
57  pybind11::finalize_interpreter();
58  }
59  }
60 
62  // pybind11::scoped_interpreter guard{};
64  theMainModule.attr("processDesc") = this;
65  theMainModule.attr("processPSet") = &theProcessPSet;
66  }
67 
69  try {
70  // if it ends with py, it's a file
71  if (config.substr(config.size() - 3) == ".py") {
72  readFile(config);
73  } else {
74  readString(config);
75  }
76  } catch (pybind11::error_already_set const& e) {
77  cmspython3::pythonToCppException("Configuration", e.what());
78  }
79  }
80 
82  pybind11::eval_file(fileName);
83  std::string command("process.fillProcessDesc(processPSet)");
84  pybind11::exec(command);
85  }
86 
88  std::string command = pyConfig;
89  command += "\nprocess.fillProcessDesc(processPSet)";
90  pybind11::exec(command.c_str());
91  }
92 
93  std::unique_ptr<edm::ParameterSet> PyBind11ProcessDesc::parameterSet() const {
94  return std::make_unique<edm::ParameterSet>(theProcessPSet.pset());
95  }
96 
98  std::ostringstream os;
99  os << theProcessPSet.dump();
100  return os.str();
101  }
102 
103  // For backward compatibility only. Remove when no longer used.
104  std::unique_ptr<edm::ProcessDesc> PyBind11ProcessDesc::processDesc() const {
105  return std::make_unique<edm::ProcessDesc>(parameterSet());
106  }
107 } // namespace cmspython3
void pythonToCppException(const std::string &iType, const std::string &error)
Definition: config.py:1
void readString(std::string const &pyConfig)
void readFile(std::string const &fileName)
std::unique_ptr< edm::ParameterSet > parameterSet() const
cond::Hash import(Session &source, const cond::Hash &sourcePayloadId, const std::string &inputTypeName, const void *inputPtr, Session &destination)
Definition: CondDBImport.cc:39
list command
Definition: mps_check.py:25
std::unique_ptr< edm::ProcessDesc > processDesc() const
void read(std::string const &config)