Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2023-03-17 11:03:33

0001 #include "FWCore/PythonParameterSet/interface/MakePyBind11ParameterSets.h"
0002 #include "FWCore/ParameterSet/interface/ParameterSet.h"
0003 
0004 #include "FWCore/PythonParameterSet/interface/Python11ParameterSet.h"
0005 #include "FWCore/PythonParameterSet/interface/PyBind11ProcessDesc.h"
0006 #include "initializePyBind11Module.h"
0007 #include <pybind11/embed.h>
0008 
0009 static void makePSetsFromFile(std::string const& fileName) {
0010   std::string initCommand(
0011       "from FWCore.ParameterSet.Types import makeCppPSet\n"
0012       "exec(open('");
0013   initCommand += fileName + "').read())";
0014   pybind11::exec(initCommand);
0015   pybind11::exec("makeCppPSet(locals(), topPSet)");
0016 }
0017 
0018 static void makePSetsFromString(std::string const& module) {
0019   std::string command = module;
0020   command += "\nfrom FWCore.ParameterSet.Types import makeCppPSet\nmakeCppPSet(locals(), topPSet)";
0021   pybind11::exec(command);
0022 }
0023 
0024 namespace edm {
0025   namespace cmspybind11 {
0026     std::unique_ptr<ParameterSet> readConfig(std::string const& config) {
0027       PyBind11ProcessDesc pythonProcessDesc(config);
0028       return pythonProcessDesc.parameterSet();
0029     }
0030 
0031     std::unique_ptr<ParameterSet> readConfig(std::string const& config, int argc, char* argv[]) {
0032       PyBind11ProcessDesc pythonProcessDesc(config, argc, argv);
0033       return pythonProcessDesc.parameterSet();
0034     }
0035 
0036     void makeParameterSets(std::string const& configtext, std::unique_ptr<ParameterSet>& main) {
0037       PyBind11ProcessDesc pythonProcessDesc(configtext);
0038       main = pythonProcessDesc.parameterSet();
0039     }
0040 
0041     std::unique_ptr<ParameterSet> readPSetsFrom(std::string const& module) {
0042       pybind11::scoped_interpreter guard{};
0043       python::initializePyBind11Module();
0044       std::unique_ptr<ParameterSet> retVal;
0045       {
0046         Python11ParameterSet theProcessPSet;
0047         pybind11::object mainModule = pybind11::module::import("__main__");
0048         mainModule.attr("topPSet") = pybind11::cast(&theProcessPSet);
0049 
0050         try {
0051           // if it ends with py, it's a file
0052           if (module.substr(module.size() - 3) == ".py") {
0053             makePSetsFromFile(module);
0054           } else {
0055             makePSetsFromString(module);
0056           }
0057         } catch (pybind11::error_already_set const& e) {
0058           pythonToCppException("Configuration", e.what());
0059         }
0060         retVal = std::make_unique<edm::ParameterSet>(ParameterSet(theProcessPSet.pset()));
0061       }
0062       return retVal;
0063     }
0064   }  // namespace cmspybind11
0065 }  // namespace edm