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// Standard
25#include <stdio.h>
26#include <Riostream.h>
27#include <string>
28
29/// \class TPython
30/// Accessing the Python interpreter from C++.
31///
32/// The TPython class allows for access to python objects from Cling. The current
33/// functionality is only basic: ROOT objects and builtin types can freely cross
34/// the boundary between the two interpreters, python objects can be instantiated
35/// and their methods can be called. All other cross-coding is based on strings
36/// that are run on the python interpreter.
37///
38/// Examples:
39///
40/// ~~~{.cpp}
41/// $ root -l
42/// // Execute a string of python code.
43/// root [0] TPython::Exec( "print(\'Hello World!\')" );
44/// Hello World!
45///
46/// // Create a TBrowser on the python side, and transfer it back and forth.
47/// // Note the required explicit (void*) cast!
48/// root [1] TBrowser* b = (void*)TPython::Eval( "ROOT.TBrowser()" );
49/// root [2] TPython::Bind( b, "b" );
50/// root [3] b == (void*) TPython::Eval( "b" )
51/// (int)1
52///
53/// // Builtin variables can cross-over by using implicit casts.
54/// root [4] int i = TPython::Eval( "1 + 1" );
55/// root [5] i
56/// (int)2
57/// ~~~
58///
59/// And with a python file `MyPyClass.py` like this:
60/// ~~~{.py}
61/// print 'creating class MyPyClass ... '
62///
63/// class MyPyClass:
64/// def __init__( self ):
65/// print 'in MyPyClass.__init__'
66///
67/// def gime( self, what ):
68/// return what
69/// ~~~
70/// one can load a python module, and use the class. Casts are
71/// necessary as the type information can not be otherwise derived.
72/// ~~~{.cpp}
73/// root [6] TPython::LoadMacro( "MyPyClass.py" );
74/// creating class MyPyClass ...
75/// root [7] MyPyClass m;
76/// in MyPyClass.__init__
77/// root [8] std::string s = (char*)m.gime( "aap" );
78/// root [9] s
79/// (class TString)"aap"
80/// ~~~
81/// It is possible to switch between interpreters by calling `TPython::Prompt()`
82/// on the Cling side, while returning with `^D` (EOF). State is preserved between
83/// successive switches.
84///
85/// The API part provides (direct) C++ access to the bindings functionality of
86/// PyROOT. It allows verifying that you deal with a PyROOT python object in the
87/// first place (CPPInstance_Check for CPPInstance and any derived types, as well
88/// as CPPInstance_CheckExact for CPPInstance's only); and it allows conversions
89/// of `void*` to an CPPInstance and vice versa.
90
91//- data ---------------------------------------------------------------------
93static PyObject *gMainDict = 0;
94
95namespace {
96
97class CachedPyString {
98
99public:
100 CachedPyString(const char *name) : fObj{PyUnicode_FromString(name)} {}
101
102 CachedPyString(CachedPyString const&) = delete;
103 CachedPyString(CachedPyString &&) = delete;
104 CachedPyString& operator=(CachedPyString const&) = delete;
105 CachedPyString& operator=(CachedPyString &&) = delete;
106
107 ~CachedPyString() { Py_DECREF(fObj); }
108
109 PyObject *obj() { return fObj; }
110
111private:
112 PyObject *fObj = nullptr;
113};
114
115namespace PyStrings {
116PyObject *basesStr()
117{
118 static CachedPyString wrapper{"__bases__"};
119 return wrapper.obj();
120}
121PyObject *cppNameStr()
122{
123 static CachedPyString wrapper{"__cpp_name__"};
124 return wrapper.obj();
125}
126PyObject *moduleStr()
127{
128 static CachedPyString wrapper{"__module__"};
129 return wrapper.obj();
130}
131PyObject *nameStr()
132{
133 static CachedPyString wrapper{"__name__"};
134 return wrapper.obj();
135}
136} // namespace PyStrings
137
138} // namespace
139
140//- static public members ----------------------------------------------------
141/// Initialization method: setup the python interpreter and load the
142/// ROOT module.
144{
145 static Bool_t isInitialized = kFALSE;
146 if (isInitialized)
147 return kTRUE;
148
149 if (!Py_IsInitialized()) {
150// this happens if Cling comes in first
151#if PY_VERSION_HEX < 0x03020000
152 PyEval_InitThreads();
153#endif
154
155// set the command line arguments on python's sys.argv
156#if PY_VERSION_HEX < 0x03000000
157 char *argv[] = {const_cast<char *>("root")};
158#else
159 wchar_t *argv[] = {const_cast<wchar_t *>(L"root")};
160#endif
161 int argc = sizeof(argv) / sizeof(argv[0]);
162#if PY_VERSION_HEX < 0x030b0000
163 Py_Initialize();
164#else
165 PyStatus status;
166 PyConfig config;
167
168 PyConfig_InitPythonConfig(&config);
169
170 status = PyConfig_SetArgv(&config, argc, argv);
171 if (PyStatus_Exception(status)) {
172 PyConfig_Clear(&config);
173 std::cerr << "Error when setting command line arguments." << std::endl;
174 return kFALSE;
175 }
176
177 status = Py_InitializeFromConfig(&config);
178 if (PyStatus_Exception(status)) {
179 PyConfig_Clear(&config);
180 std::cerr << "Error when initializing Python." << std::endl;
181 return kFALSE;
182 }
183 PyConfig_Clear(&config);
184#endif
185#if PY_VERSION_HEX >= 0x03020000
186#if PY_VERSION_HEX < 0x03090000
187 PyEval_InitThreads();
188#endif
189#endif
190
191 // try again to see if the interpreter is initialized
192 if (!Py_IsInitialized()) {
193 // give up ...
194 std::cerr << "Error: python has not been intialized; returning." << std::endl;
195 return kFALSE;
196 }
197
198#if PY_VERSION_HEX < 0x030b0000
199 PySys_SetArgv(argc, argv);
200#endif
201
202 // force loading of the ROOT module
203 const int ret = PyRun_SimpleString(const_cast<char *>("import ROOT"));
204 if( ret != 0 )
205 {
206 std::cerr << "Error: import ROOT failed, check your PYTHONPATH environmental variable." << std::endl;
207 return kFALSE;
208 }
209 }
210
211 if (!gMainDict) {
212 // retrieve the main dictionary
213 gMainDict = PyModule_GetDict(PyImport_AddModule(const_cast<char *>("__main__")));
214 Py_INCREF(gMainDict);
215 }
216
217 // python side class construction, managed by ROOT
218 gROOT->AddClassGenerator(new TPyClassGenerator);
219
220 // declare success ...
221 isInitialized = kTRUE;
222 return kTRUE;
223}
224
225////////////////////////////////////////////////////////////////////////////////
226/// Import the named python module and create Cling equivalents for its classes
227/// and methods.
228
229Bool_t TPython::Import(const char *mod_name)
230{
231 if (!CPyCppyy::Import(mod_name)) {
232 return false;
233 }
234
235 // force creation of the module as a namespace
236 TClass::GetClass(mod_name, kTRUE);
237
238 PyObject *modNameObj = PyUnicode_FromString(mod_name);
239 PyObject *mod = PyImport_GetModule(modNameObj);
240 PyObject *dct = PyModule_GetDict(mod);
241
242 // create Cling classes for all new python classes
243 PyObject *values = PyDict_Values(dct);
244 for (int i = 0; i < PyList_GET_SIZE(values); ++i) {
245 PyObject *value = PyList_GET_ITEM(values, i);
246 Py_INCREF(value);
247
248 // collect classes
249 if (PyType_Check(value) || PyObject_HasAttr(value, PyStrings::basesStr())) {
250 // get full class name (including module)
251 PyObject *pyClName = PyObject_GetAttr(value, PyStrings::cppNameStr());
252 if (!pyClName) {
253 pyClName = PyObject_GetAttr(value, PyStrings::nameStr());
254 }
255
256 if (PyErr_Occurred())
257 PyErr_Clear();
258
259 // build full, qualified name
260 std::string fullname = mod_name;
261 fullname += ".";
262 fullname += PyUnicode_AsUTF8(pyClName);
263
264 // force class creation (this will eventually call TPyClassGenerator)
265 TClass::GetClass(fullname.c_str(), kTRUE);
266
267 Py_XDECREF(pyClName);
268 }
269
270 Py_DECREF(value);
271 }
272
273 Py_DECREF(values);
274 Py_DECREF(mod);
275 Py_DECREF(modNameObj);
276
277 if (PyErr_Occurred())
278 return kFALSE;
279 return kTRUE;
280}
281
282////////////////////////////////////////////////////////////////////////////////
283/// Execute the give python script as if it were a macro (effectively an
284/// execfile in __main__), and create Cling equivalents for any newly available
285/// python classes.
286
287void TPython::LoadMacro(const char *name)
288{
289 // setup
290 if (!Initialize())
291 return;
292
293 // obtain a reference to look for new classes later
294 PyObject *old = PyDict_Values(gMainDict);
295
296// actual execution
297#if PY_VERSION_HEX < 0x03000000
298 Exec((std::string("execfile(\"") + name + "\")").c_str());
299#else
300 Exec((std::string("__pyroot_f = open(\"") + name + "\"); "
301 "exec(__pyroot_f.read()); "
302 "__pyroot_f.close(); del __pyroot_f")
303 .c_str());
304#endif
305
306 // obtain new __main__ contents
307 PyObject *current = PyDict_Values(gMainDict);
308
309 // create Cling classes for all new python classes
310 for (int i = 0; i < PyList_GET_SIZE(current); ++i) {
311 PyObject *value = PyList_GET_ITEM(current, i);
312 Py_INCREF(value);
313
314 if (!PySequence_Contains(old, value)) {
315 // collect classes
316 if (PyType_Check(value) || PyObject_HasAttr(value, PyStrings::basesStr())) {
317 // get full class name (including module)
318 PyObject *pyModName = PyObject_GetAttr(value, PyStrings::moduleStr());
319 PyObject *pyClName = PyObject_GetAttr(value, PyStrings::nameStr());
320
321 if (PyErr_Occurred())
322 PyErr_Clear();
323
324 // need to check for both exact and derived (differences exist between older and newer
325 // versions of python ... bug?)
326 if ((pyModName && pyClName) &&
327 ((PyUnicode_CheckExact(pyModName) && PyUnicode_CheckExact(pyClName)) ||
328 (PyUnicode_Check(pyModName) && PyUnicode_Check(pyClName)))) {
329 // build full, qualified name
330 std::string fullname = PyUnicode_AsUTF8(pyModName);
331 fullname += '.';
332 fullname += PyUnicode_AsUTF8(pyClName);
333
334 // force class creation (this will eventually call TPyClassGenerator)
335 TClass::GetClass(fullname.c_str(), kTRUE);
336 }
337
338 Py_XDECREF(pyClName);
339 Py_XDECREF(pyModName);
340 }
341 }
342
343 Py_DECREF(value);
344 }
345
346 Py_DECREF(current);
347 Py_DECREF(old);
348}
349
350////////////////////////////////////////////////////////////////////////////////
351/// Execute a python stand-alone script, with argv CLI arguments.
352///
353/// example of use:
354/// const char* argv[] = { "1", "2", "3" };
355/// TPython::ExecScript( "test.py", sizeof(argv)/sizeof(argv[0]), argv );
356
357void TPython::ExecScript(const char *name, int argc, const char **argv)
358{
359
360 // setup
361 if (!Initialize())
362 return;
363
364 // verify arguments
365 if (!name) {
366 std::cerr << "Error: no file name specified." << std::endl;
367 return;
368 }
369
370 std::vector<std::string> args(argc);
371 for (int i = 0; i < argc; ++i) {
372 args[i] = argv[i];
373 }
375}
376
377////////////////////////////////////////////////////////////////////////////////
378/// Execute a python statement (e.g. "import ROOT").
379
380Bool_t TPython::Exec(const char *cmd)
381{
382 // setup
383 if (!Initialize())
384 return kFALSE;
385
386 // execute the command
387 PyObject *result = PyRun_String(const_cast<char *>(cmd), Py_file_input, gMainDict, gMainDict);
388
389 // test for error
390 if (result) {
391 Py_DECREF(result);
392 return kTRUE;
393 }
394
395 PyErr_Print();
396 return kFALSE;
397}
398
399////////////////////////////////////////////////////////////////////////////////
400/// Evaluate a python expression (e.g. "ROOT.TBrowser()").
401///
402/// Caution: do not hold on to the return value: either store it in a builtin
403/// type (implicit casting will work), or in a pointer to a ROOT object (explicit
404/// casting to a void* is required).
405
406const TPyReturn TPython::Eval(const char *expr)
407{
408 // setup
409 if (!Initialize())
410 return TPyReturn();
411
412 // evaluate the expression
413 PyObject *result = PyRun_String(const_cast<char *>(expr), Py_eval_input, gMainDict, gMainDict);
414
415 // report errors as appropriate; return void
416 if (!result) {
417 PyErr_Print();
418 return TPyReturn();
419 }
420
421 // results that require no conversion
422 if (result == Py_None || CPyCppyy::Instance_Check(result) || PyBytes_Check(result) || PyFloat_Check(result) ||
423 PyLong_Check(result))
424 return TPyReturn(result);
425
426 // explicit conversion for python type required
427 PyObject *pyclass = PyObject_GetAttrString(result, const_cast<char*>("__class__"));
428 if (pyclass != 0) {
429 // retrieve class name and the module in which it resides
430 PyObject *name = PyObject_GetAttr(pyclass, PyStrings::nameStr());
431 PyObject *module = PyObject_GetAttr(pyclass, PyStrings::moduleStr());
432
433 // concat name
434 std::string qname = std::string(PyUnicode_AsUTF8(module)) + '.' + PyUnicode_AsUTF8(name);
435 Py_DECREF(module);
436 Py_DECREF(name);
437 Py_DECREF(pyclass);
438
439 // locate ROOT style class with this name
440 TClass *klass = TClass::GetClass(qname.c_str());
441
442 // construct general ROOT python object that pretends to be of class 'klass'
443 if (klass != 0)
444 return TPyReturn(result);
445 } else
446 PyErr_Clear();
447
448 // no conversion, return null pointer object
449 Py_DECREF(result);
450 return TPyReturn();
451}
452
453////////////////////////////////////////////////////////////////////////////////
454/// Bind a ROOT object with, at the python side, the name "label".
455
456Bool_t TPython::Bind(TObject *object, const char *label)
457{
458 // check given address and setup
459 if (!(object && Initialize()))
460 return kFALSE;
461
462 // bind object in the main namespace
463 TClass *klass = object->IsA();
464 if (klass != 0) {
465 PyObject *bound = CPyCppyy::Instance_FromVoidPtr((void *)object, klass->GetName());
466
467 if (bound) {
468 Bool_t bOk = PyDict_SetItemString(gMainDict, const_cast<char *>(label), bound) == 0;
469 Py_DECREF(bound);
470
471 return bOk;
472 }
473 }
474
475 return kFALSE;
476}
477
478////////////////////////////////////////////////////////////////////////////////
479/// Enter an interactive python session (exit with ^D). State is preserved
480/// between successive calls.
481
483{
484 // setup
485 if (!Initialize()) {
486 return;
487 }
488
489 // enter i/o interactive mode
490 PyRun_InteractiveLoop(stdin, const_cast<char *>("\0"));
491}
492
493////////////////////////////////////////////////////////////////////////////////
494/// Test whether the type of the given pyobject is of CPPInstance type or any
495/// derived type.
496
498{
499 // setup
500 if (!Initialize())
501 return kFALSE;
502
503 // detailed walk through inheritance hierarchy
504 return CPyCppyy::Instance_Check(pyobject);
505}
506
507////////////////////////////////////////////////////////////////////////////////
508/// Test whether the type of the given pyobject is CPPinstance type.
509
511{
512 // setup
513 if (!Initialize())
514 return kFALSE;
515
516 // direct pointer comparison of type member
517 return CPyCppyy::Instance_CheckExact(pyobject);
518}
519
520////////////////////////////////////////////////////////////////////////////////
521/// Test whether the type of the given pyobject is of CPPOverload type or any
522/// derived type.
523
525{
526 // setup
527 if (!Initialize())
528 return kFALSE;
529
530 // detailed walk through inheritance hierarchy
531 return CPyCppyy::Overload_Check(pyobject);
532}
533
534////////////////////////////////////////////////////////////////////////////////
535/// Test whether the type of the given pyobject is CPPOverload type.
536
538{
539 // setup
540 if (!Initialize())
541 return kFALSE;
542
543 // direct pointer comparison of type member
544 return CPyCppyy::Overload_CheckExact(pyobject);
545}
546
547////////////////////////////////////////////////////////////////////////////////
548/// Extract the object pointer held by the CPPInstance pyobject.
549
551{
552 // setup
553 if (!Initialize())
554 return 0;
555
556 // get held object (may be null)
557 return CPyCppyy::Instance_AsVoidPtr(pyobject);
558}
559
560////////////////////////////////////////////////////////////////////////////////
561/// Bind the addr to a python object of class defined by classname.
562
563PyObject *TPython::CPPInstance_FromVoidPtr(void *addr, const char *classname, Bool_t python_owns)
564{
565 // setup
566 if (!Initialize())
567 return 0;
568
569 // perform cast (the call will check TClass and addr, and set python errors)
570 // give ownership, for ref-counting, to the python side, if so requested
571 return CPyCppyy::Instance_FromVoidPtr(addr, classname, python_owns);
572}
#define PyBytes_Check
Definition CPyCppyy.h:61
_object PyObject
constexpr Bool_t kFALSE
Definition RtypesCore.h:101
constexpr Bool_t kTRUE
Definition RtypesCore.h:100
#define ClassImp(name)
Definition Rtypes.h:377
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:93
Binding & operator=(OUT(*fun)(void))
#define gROOT
Definition TROOT.h:406
TClass instances represent classes, structs and namespaces in the ROOT type system.
Definition TClass.h:81
TClass * IsA() const override
Definition TClass.h:618
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:2968
const char * GetName() const override
Returns name of object.
Definition TNamed.h:47
Mother of all ROOT objects.
Definition TObject.h:41
Accessing the Python interpreter from C++.
Definition TPython.h:29
static void Prompt()
Enter an interactive python session (exit with ^D).
Definition TPython.cxx:482
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:524
static void * CPPInstance_AsVoidPtr(PyObject *pyobject)
Extract the object pointer held by the CPPInstance pyobject.
Definition TPython.cxx:550
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:357
static Bool_t Import(const char *name)
Import the named python module and create Cling equivalents for its classes and methods.
Definition TPython.cxx:229
static Bool_t CPPInstance_CheckExact(PyObject *pyobject)
Test whether the type of the given pyobject is CPPinstance type.
Definition TPython.cxx:510
static Bool_t Bind(TObject *object, const char *label)
Bind a ROOT object with, at the python side, the name "label".
Definition TPython.cxx:456
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:287
static Bool_t CPPOverload_CheckExact(PyObject *pyobject)
Test whether the type of the given pyobject is CPPOverload type.
Definition TPython.cxx:537
static Bool_t Initialize()
Initialization method: setup the python interpreter and load the ROOT module.
Definition TPython.cxx:143
static Bool_t Exec(const char *cmd)
Execute a python statement (e.g. "import ROOT").
Definition TPython.cxx:380
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:497
static const TPyReturn Eval(const char *expr)
Evaluate a python expression (e.g.
Definition TPython.cxx:406
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:563
CPYCPPYY_EXTERN bool Instance_CheckExact(PyObject *pyobject)
Definition API.cxx:174
CPYCPPYY_EXTERN bool Overload_Check(PyObject *pyobject)
Definition API.cxx:233
CPYCPPYY_EXTERN bool Overload_CheckExact(PyObject *pyobject)
Definition API.cxx:244
CPYCPPYY_EXTERN bool Import(const std::string &name)
Definition API.cxx:256
CPYCPPYY_EXTERN void ExecScript(const std::string &name, const std::vector< std::string > &args)
Definition API.cxx:315
CPYCPPYY_EXTERN bool Instance_Check(PyObject *pyobject)
Definition API.cxx:163
CPYCPPYY_EXTERN PyObject * Instance_FromVoidPtr(void *addr, const std::string &classname, bool python_owns=false)
Definition API.cxx:118
CPYCPPYY_EXTERN void * Instance_AsVoidPtr(PyObject *pyobject)
Definition API.cxx:103