Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TPython.cxx
Go to the documentation of this file.
1// Author: Enric Tejedor CERN 08/2019
2// Original PyROOT code by Wim Lavrijsen, LBL
3//
4// /*************************************************************************
5// * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *
6// * All rights reserved. *
7// * *
8// * For the licensing terms see $ROOTSYS/LICENSE. *
9// * For the list of contributors see $ROOTSYS/README/CREDITS. *
10// *************************************************************************/
11
12// Bindings
13// CPyCppyy.h must be go first, since it includes Python.h, which must be
14// included before any standard header
15#include "CPyCppyy/API.h"
16#include "TPython.h"
17#include "TPyClassGenerator.h"
18
19// ROOT
20#include "TROOT.h"
21#include "TClassRef.h"
22#include "TObject.h"
23
24#include <Riostream.h>
25
26// Standard
27#include <mutex>
28#include <sstream>
29#include <stdio.h>
30#include <string>
31
32/// \class TPython
33/// Accessing the Python interpreter from C++.
34///
35/// The TPython class allows for access to python objects from Cling. The current
36/// functionality is only basic: ROOT objects and builtin types can freely cross
37/// the boundary between the two interpreters, python objects can be instantiated
38/// and their methods can be called. All other cross-coding is based on strings
39/// that are run on the python interpreter.
40///
41/// Examples:
42///
43/// ~~~{.cpp}
44/// $ root -l
45/// // Execute a string of python code.
46/// root [0] TPython::Exec( "print('Hello World!')" );
47/// Hello World!
48///
49/// // Create a TNamed on the python side, and transfer it back and forth.
50/// root [1] std::any res1;
51/// root [2] TPython::Exec("_anyresult = ROOT.std.make_any['TNamed']('hello', '')", &res1);
52/// root [3] TPython::Bind(&std::any_cast<TNamed&>(res1), "n");
53/// root [4] std::any res2;
54/// root [5] TPython::Exec("_anyresult = ROOT.std.make_any['TNamed*', 'TNamed*'](n)", &res2);
55/// root [6] (&std::any_cast<TNamed&>(res1) == std::any_cast<TNamed*>(res2))
56/// (bool) true
57///
58/// // Variables can cross-over by using an `std::any` with a specific name.
59/// root [6] TPython::Exec("_anyresult = ROOT.std.make_any['Int_t'](1 + 1)", &res1);
60/// root [7] std::any_cast<int>(res1)
61/// (int) 2
62/// ~~~
63///
64/// And with a python file `MyPyClass.py` like this:
65/// ~~~{.py}
66/// print 'creating class MyPyClass ... '
67///
68/// class MyPyClass:
69/// def __init__( self ):
70/// print 'in MyPyClass.__init__'
71///
72/// def gime( self, what ):
73/// return what
74/// ~~~
75/// one can load a python module, and use the class. Casts are
76/// necessary as the type information can not be otherwise derived.
77/// ~~~{.cpp}
78/// root [6] TPython::LoadMacro( "MyPyClass.py" );
79/// creating class MyPyClass ...
80/// root [7] MyPyClass m;
81/// in MyPyClass.__init__
82/// root [8] std::string s = (char*)m.gime( "aap" );
83/// root [9] s
84/// (class TString)"aap"
85/// ~~~
86/// It is possible to switch between interpreters by calling `TPython::Prompt()`
87/// on the Cling side, while returning with `^D` (EOF). State is preserved between
88/// successive switches.
89///
90/// The API part provides (direct) C++ access to the bindings functionality of
91/// PyROOT. It allows verifying that you deal with a PyROOT python object in the
92/// first place (CPPInstance_Check for CPPInstance and any derived types, as well
93/// as CPPInstance_CheckExact for CPPInstance's only); and it allows conversions
94/// of `void*` to an CPPInstance and vice versa.
95
96//- data ---------------------------------------------------------------------
97static PyObject *gMainDict = 0;
98
99namespace {
100
102
103// To acquire the GIL as described here:
104// https://docs.python.org/3/c-api/init.html#non-python-created-threads
105class PyGILRAII {
106 PyGILState_STATE m_GILState;
107
108public:
109 PyGILRAII() : m_GILState(PyGILState_Ensure()) {}
110 ~PyGILRAII() { PyGILState_Release(m_GILState); }
111};
112
113struct PyObjDeleter {
114 void operator()(PyObject* obj) const {
115 Py_DecRef(obj);
116 }
117};
118
119using PyObjectRef = std::unique_ptr<PyObject, PyObjDeleter>;
120
121} // namespace
122
123//- static public members ----------------------------------------------------
124/// Initialization method: setup the python interpreter and load the
125/// ROOT module.
127{
128 // Don't initialize Python from two concurrent threads
129 static std::mutex initMutex;
130 const std::lock_guard<std::mutex> lock(initMutex);
131
132 static Bool_t isInitialized = false;
133 if (isInitialized)
134 return true;
135
136 if (!Py_IsInitialized()) {
137 wchar_t rootStr[] = L"root";
138 wchar_t *argv[] = {rootStr};
139 int argc = sizeof(argv) / sizeof(argv[0]);
140#if PY_VERSION_HEX < 0x030b0000
142#else
143 PyStatus status;
144 PyConfig config;
145
147
148 status = PyConfig_SetArgv(&config, argc, argv);
149 if (PyStatus_Exception(status)) {
150 PyConfig_Clear(&config);
151 std::cerr << "Error when setting command line arguments." << std::endl;
152 return false;
153 }
154
155 status = Py_InitializeFromConfig(&config);
156 if (PyStatus_Exception(status)) {
157 PyConfig_Clear(&config);
158 std::cerr << "Error when initializing Python." << std::endl;
159 return false;
160 }
161 PyConfig_Clear(&config);
162#endif
163
164 // try again to see if the interpreter is initialized
165 if (!Py_IsInitialized()) {
166 // give up ...
167 std::cerr << "Error: python has not been intialized; returning." << std::endl;
168 return false;
169 }
170
171#if PY_VERSION_HEX < 0x030b0000
173#endif
174
176 }
177
178 {
179 // For the Python API calls
180 PyGILRAII gilRaii;
181
182 // force loading of the ROOT module
183 const int ret = PyRun_SimpleString("import ROOT");
184 if (ret != 0) {
185 std::cerr << "Error: import ROOT failed, check your PYTHONPATH environmental variable." << std::endl;
186 return false;
187 }
188
189 if (!gMainDict) {
190
191 // retrieve the main dictionary
193 // The gMainDict is borrowed, i.e. we are not calling Py_IncRef(gMainDict).
194 // Like this, we avoid unexpectedly affecting how long __main__ is kept
195 // alive. The gMainDict is only used in Exec(), ExecScript(), and Eval(),
196 // which should not be called after __main__ is garbage collected anyway.
197 }
198 }
199
200 // python side class construction, managed by ROOT
201 gROOT->AddClassGenerator(new TPyClassGenerator);
202
203 // declare success ...
204 isInitialized = true;
205 return true;
206}
207
208////////////////////////////////////////////////////////////////////////////////
209/// Import the named python module and create Cling equivalents for its classes
210/// and methods.
211
213{
214 // setup
215 if (!Initialize())
216 return false;
217
218 PyGILRAII gilRaii;
219
221 return false;
222 }
223
224 // force creation of the module as a namespace
226
230
234
235 // create Cling classes for all new python classes
237 for (int i = 0; i < PyList_Size(values.get()); ++i) {
238 PyObjectRef value{PyList_GetItem(values.get(), i)};
239 Py_IncRef(value.get());
240
241 // collect classes
242 if (PyType_Check(value.get()) || PyObject_HasAttr(value.get(), basesStr.get())) {
243 // get full class name (including module)
245 if (!pyClName) {
246 if (PyErr_Occurred())
247 PyErr_Clear();
249 }
250
251 if (PyErr_Occurred())
252 PyErr_Clear();
253
254 // build full, qualified name
255 std::string fullname = mod_name;
256 fullname += ".";
257 fullname += PyUnicode_AsUTF8AndSize(pyClName.get(), nullptr);
258
259 // force class creation (this will eventually call TPyClassGenerator)
260 TClass::GetClass(fullname.c_str(), true);
261 }
262 }
263
264 return !PyErr_Occurred();
265}
266
267////////////////////////////////////////////////////////////////////////////////
268/// Execute the give python script as if it were a macro (effectively an
269/// execfile in __main__), and create Cling equivalents for any newly available
270/// python classes.
271
272void TPython::LoadMacro(const char *name)
273{
274 // setup
275 if (!Initialize())
276 return;
277
278 PyGILRAII gilRaii;
279
280 // obtain a reference to look for new classes later
282
283// actual execution
284 Exec((std::string("__pyroot_f = open(\"") + name +
285 "\"); "
286 "exec(__pyroot_f.read()); "
287 "__pyroot_f.close(); del __pyroot_f")
288 .c_str());
289
290 // obtain new __main__ contents
292
296
297 // create Cling classes for all new python classes
298 for (int i = 0; i < PyList_Size(current.get()); ++i) {
299 PyObjectRef value{PyList_GetItem(current.get(), i)};
300 Py_IncRef(value.get());
301
302 if (!PySequence_Contains(old.get(), value.get())) {
303 // collect classes
304 if (PyType_Check(value.get()) || PyObject_HasAttr(value.get(), basesStr.get())) {
305 // get full class name (including module)
308
309 if (PyErr_Occurred())
310 PyErr_Clear();
311
312 // need to check for both exact and derived (differences exist between older and newer
313 // versions of python ... bug?)
316 // build full, qualified name
317 std::string fullname = PyUnicode_AsUTF8AndSize(pyModName.get(), nullptr);
318 fullname += '.';
319 fullname += PyUnicode_AsUTF8AndSize(pyClName.get(), nullptr);
320
321 // force class creation (this will eventually call TPyClassGenerator)
322 TClass::GetClass(fullname.c_str(), true);
323 }
324 }
325 }
326 }
327}
328
329////////////////////////////////////////////////////////////////////////////////
330/// Execute a python stand-alone script, with argv CLI arguments.
331///
332/// example of use:
333/// const char* argv[] = { "1", "2", "3" };
334/// TPython::ExecScript( "test.py", sizeof(argv)/sizeof(argv[0]), argv );
335
336void TPython::ExecScript(const char *name, int argc, const char **argv)
337{
338
339 // setup
340 if (!Initialize())
341 return;
342
343 PyGILRAII gilRaii;
344
345 // verify arguments
346 if (!name) {
347 std::cerr << "Error: no file name specified." << std::endl;
348 return;
349 }
350
351 std::vector<std::string> args(argc);
352 for (int i = 0; i < argc; ++i) {
353 args[i] = argv[i];
354 }
356}
357
358////////////////////////////////////////////////////////////////////////////////
359/// Executes a Python command within the current Python environment.
360///
361/// This function initializes the Python environment if it is not already
362/// initialized. It then executes the specified Python command string using the
363/// Python C API.
364///
365/// In the Python command, you can change the value of a special TPyResult
366/// object returned by TPyBuffer(). If the optional result parameter is
367/// non-zero, the result parameter will be swapped with a std::any variable on
368/// the Python side. You need to define this variable yourself, and it needs to
369/// be of type std::any and its name needs to be `"_anyresult"` by default.
370/// Like this, you can pass information from Python back to C++.
371///
372/// \param cmd The Python command to be executed as a string.
373/// \param result Optional pointer to a std::any object that can be used to
374/// transfer results from Python to C++.
375/// \param resultName Name of the Python variable that is swapped over to the std::any result.
376/// The default value is `"_anyresult"`.
377/// \return bool Returns `true` if the command was successfully executed,
378/// otherwise returns `false`.
379
380Bool_t TPython::Exec(const char *cmd, std::any *result, std::string const &resultName)
381{
382 // setup
383 if (!Initialize())
384 return false;
385
386 PyGILRAII gilRaii;
387
388 std::stringstream command;
389 // Add the actual command
390 command << cmd;
391 // Swap the std::any with the one in the C++ world if required
392 if (result) {
393 command << "; ROOT.Internal.SwapWithObjAtAddr['std::any'](" << resultName << ", "
394 << reinterpret_cast<std::intptr_t>(result) << ")";
395 }
396
397 // execute the command
400
401 // test for error
402 if (pyObjectResult) {
403 return true;
404 }
405
406 PyErr_Print();
407 return false;
408}
409
410////////////////////////////////////////////////////////////////////////////////
411/// Bind a ROOT object with, at the python side, the name "label".
412
413Bool_t TPython::Bind(TObject *object, const char *label)
414{
415 // check given address and setup
416 if (!(object && Initialize()))
417 return false;
418
419 PyGILRAII gilRaii;
420
421 // bind object in the main namespace
422 TClass *klass = object->IsA();
423 if (klass != 0) {
424 PyObjectRef bound{CPyCppyy::Instance_FromVoidPtr((void *)object, klass->GetName())};
425
426 if (bound) {
427 Bool_t bOk = PyDict_SetItemString(gMainDict, label, bound.get()) == 0;
428
429 return bOk;
430 }
431 }
432
433 return false;
434}
435
436////////////////////////////////////////////////////////////////////////////////
437/// Enter an interactive python session (exit with ^D). State is preserved
438/// between successive calls.
439
441{
442 // setup
443 if (!Initialize()) {
444 return;
445 }
446
447 PyGILRAII gilRaii;
448
449 // enter i/o interactive mode
451}
452
453////////////////////////////////////////////////////////////////////////////////
454/// Test whether the type of the given pyobject is of CPPInstance type or any
455/// derived type.
456
458{
459 // setup
460 if (!Initialize())
461 return false;
462
463 PyGILRAII gilRaii;
464
465 // detailed walk through inheritance hierarchy
467}
468
469////////////////////////////////////////////////////////////////////////////////
470/// Test whether the type of the given pyobject is CPPinstance type.
471
473{
474 // setup
475 if (!Initialize())
476 return false;
477
478 PyGILRAII gilRaii;
479
480 // direct pointer comparison of type member
482}
483
484////////////////////////////////////////////////////////////////////////////////
485/// Test whether the type of the given pyobject is of CPPOverload type or any
486/// derived type.
487
489{
490 // setup
491 if (!Initialize())
492 return false;
493
494 PyGILRAII gilRaii;
495
496 // detailed walk through inheritance hierarchy
498}
499
500////////////////////////////////////////////////////////////////////////////////
501/// Test whether the type of the given pyobject is CPPOverload type.
502
504{
505 // setup
506 if (!Initialize())
507 return false;
508
509 PyGILRAII gilRaii;
510
511 // direct pointer comparison of type member
513}
514
515////////////////////////////////////////////////////////////////////////////////
516/// Extract the object pointer held by the CPPInstance pyobject.
517
519{
520 // setup
521 if (!Initialize())
522 return nullptr;
523
524 PyGILRAII gilRaii;
525
526 // get held object (may be null)
528}
529
530////////////////////////////////////////////////////////////////////////////////
531/// Bind the addr to a python object of class defined by classname.
532
534{
535 // setup
536 if (!Initialize())
537 return nullptr;
538
539 PyGILRAII gilRaii;
540
541 // perform cast (the call will check TClass and addr, and set python errors)
542 // give ownership, for ref-counting, to the python side, if so requested
544}
_object PyObject
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
char name[80]
Definition TGX11.cxx:110
static PyObject * gMainDict
Definition TPython.cxx:97
_object PyObject
Definition TPython.h:23
TRObject operator()(const T1 &t1) const
#define gROOT
Definition TROOT.h:414
TClass instances represent classes, structs and namespaces in the ROOT type system.
Definition TClass.h:84
static TClass * GetClass(const char *name, Bool_t load=kTRUE, Bool_t silent=kFALSE)
Static method returning pointer to TClass of the specified class name.
Definition TClass.cxx:2973
Mother of all ROOT objects.
Definition TObject.h:41
static void Prompt()
Enter an interactive python session (exit with ^D).
Definition TPython.cxx:440
static Bool_t CPPOverload_Check(PyObject *pyobject)
Test whether the type of the given pyobject is of CPPOverload type or any derived type.
Definition TPython.cxx:488
static void * CPPInstance_AsVoidPtr(PyObject *pyobject)
Extract the object pointer held by the CPPInstance pyobject.
Definition TPython.cxx:518
static void ExecScript(const char *name, int argc=0, const char **argv=nullptr)
Execute a python stand-alone script, with argv CLI arguments.
Definition TPython.cxx:336
static Bool_t Import(const char *name)
Import the named python module and create Cling equivalents for its classes and methods.
Definition TPython.cxx:212
static Bool_t CPPInstance_CheckExact(PyObject *pyobject)
Test whether the type of the given pyobject is CPPinstance type.
Definition TPython.cxx:472
static Bool_t Bind(TObject *object, const char *label)
Bind a ROOT object with, at the python side, the name "label".
Definition TPython.cxx:413
static void LoadMacro(const char *name)
Execute the give python script as if it were a macro (effectively an execfile in main),...
Definition TPython.cxx:272
static Bool_t Exec(const char *cmd, std::any *result=nullptr, std::string const &resultName="_anyresult")
Executes a Python command within the current Python environment.
Definition TPython.cxx:380
static Bool_t CPPOverload_CheckExact(PyObject *pyobject)
Test whether the type of the given pyobject is CPPOverload type.
Definition TPython.cxx:503
static Bool_t Initialize()
Initialization method: setup the python interpreter and load the ROOT module.
Definition TPython.cxx:126
static Bool_t CPPInstance_Check(PyObject *pyobject)
Test whether the type of the given pyobject is of CPPInstance type or any derived type.
Definition TPython.cxx:457
static PyObject * CPPInstance_FromVoidPtr(void *addr, const char *classname, Bool_t python_owns=kFALSE)
Bind the addr to a python object of class defined by classname.
Definition TPython.cxx:533
CPYCPPYY_EXTERN bool Instance_CheckExact(PyObject *pyobject)
Definition API.cxx:177
CPYCPPYY_EXTERN bool Overload_Check(PyObject *pyobject)
Definition API.cxx:236
CPYCPPYY_EXTERN bool Overload_CheckExact(PyObject *pyobject)
Definition API.cxx:247
CPYCPPYY_EXTERN bool Import(const std::string &name)
Definition API.cxx:259
CPYCPPYY_EXTERN void ExecScript(const std::string &name, const std::vector< std::string > &args)
Definition API.cxx:318
CPYCPPYY_EXTERN bool Instance_Check(PyObject *pyobject)
Definition API.cxx:166
CPYCPPYY_EXTERN PyObject * Instance_FromVoidPtr(void *addr, const std::string &classname, bool python_owns=false)
Definition API.cxx:121
CPYCPPYY_EXTERN void * Instance_AsVoidPtr(PyObject *pyobject)
Definition API.cxx:106