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 // escape characters in the file name that would otherwise terminate or
297 // alter the Python string literal we put the file name into below
298 std::string escapedName;
299 escapedName.reserve(std::char_traits<char>::length(name));
300 for (const char *p = name; *p; ++p) {
301 switch (*p) {
302 case '\\': escapedName += "\\\\"; break;
303 case '"': escapedName += "\\\""; break;
304 case '\n': escapedName += "\\n"; break;
305 case '\r': escapedName += "\\r"; break;
306 default: escapedName += *p; break;
307 }
308 }
309
310// actual execution
311#if PY_VERSION_HEX < 0x03000000
312 Exec((std::string("execfile(\"") + escapedName + "\")").c_str());
313#else
314 Exec((std::string("__pyroot_f = open(\"") + escapedName + "\"); "
315 "exec(__pyroot_f.read()); "
316 "__pyroot_f.close(); del __pyroot_f")
317 .c_str());
318#endif
319
320 // obtain new __main__ contents
321 PyObject *current = PyDict_Values(gMainDict);
322
323 // create Cling classes for all new python classes
324 for (int i = 0; i < PyList_GET_SIZE(current); ++i) {
325 PyObject *value = PyList_GET_ITEM(current, i);
326 Py_INCREF(value);
327
328 if (!PySequence_Contains(old, value)) {
329 // collect classes
330 if (PyType_Check(value) || PyObject_HasAttr(value, PyStrings::basesStr())) {
331 // get full class name (including module)
332 PyObject *pyModName = PyObject_GetAttr(value, PyStrings::moduleStr());
333 PyObject *pyClName = PyObject_GetAttr(value, PyStrings::nameStr());
334
335 if (PyErr_Occurred())
336 PyErr_Clear();
337
338 // need to check for both exact and derived (differences exist between older and newer
339 // versions of python ... bug?)
340 if ((pyModName && pyClName) &&
341 ((PyUnicode_CheckExact(pyModName) && PyUnicode_CheckExact(pyClName)) ||
342 (PyUnicode_Check(pyModName) && PyUnicode_Check(pyClName)))) {
343 // build full, qualified name
344 std::string fullname = PyUnicode_AsUTF8(pyModName);
345 fullname += '.';
346 fullname += PyUnicode_AsUTF8(pyClName);
347
348 // force class creation (this will eventually call TPyClassGenerator)
349 TClass::GetClass(fullname.c_str(), kTRUE);
350 }
351
352 Py_XDECREF(pyClName);
353 Py_XDECREF(pyModName);
354 }
355 }
356
357 Py_DECREF(value);
358 }
359
360 Py_DECREF(current);
361 Py_DECREF(old);
362}
363
364////////////////////////////////////////////////////////////////////////////////
365/// Execute a python stand-alone script, with argv CLI arguments.
366///
367/// example of use:
368/// const char* argv[] = { "1", "2", "3" };
369/// TPython::ExecScript( "test.py", sizeof(argv)/sizeof(argv[0]), argv );
370
371void TPython::ExecScript(const char *name, int argc, const char **argv)
372{
373
374 // setup
375 if (!Initialize())
376 return;
377
378 // verify arguments
379 if (!name) {
380 std::cerr << "Error: no file name specified." << std::endl;
381 return;
382 }
383
384 std::vector<std::string> args(argc);
385 for (int i = 0; i < argc; ++i) {
386 args[i] = argv[i];
387 }
389}
390
391////////////////////////////////////////////////////////////////////////////////
392/// Execute a python statement (e.g. "import ROOT").
393
394Bool_t TPython::Exec(const char *cmd)
395{
396 // setup
397 if (!Initialize())
398 return kFALSE;
399
400 // execute the command
401 PyObject *result = PyRun_String(const_cast<char *>(cmd), Py_file_input, gMainDict, gMainDict);
402
403 // test for error
404 if (result) {
405 Py_DECREF(result);
406 return kTRUE;
407 }
408
409 PyErr_Print();
410 return kFALSE;
411}
412
413////////////////////////////////////////////////////////////////////////////////
414/// Evaluate a python expression (e.g. "ROOT.TBrowser()").
415///
416/// Caution: do not hold on to the return value: either store it in a builtin
417/// type (implicit casting will work), or in a pointer to a ROOT object (explicit
418/// casting to a void* is required).
419
420const TPyReturn TPython::Eval(const char *expr)
421{
422 // setup
423 if (!Initialize())
424 return TPyReturn();
425
426 // evaluate the expression
427 PyObject *result = PyRun_String(const_cast<char *>(expr), Py_eval_input, gMainDict, gMainDict);
428
429 // report errors as appropriate; return void
430 if (!result) {
431 PyErr_Print();
432 return TPyReturn();
433 }
434
435 // results that require no conversion
436 if (result == Py_None || CPyCppyy::Instance_Check(result) || PyBytes_Check(result) || PyFloat_Check(result) ||
437 PyLong_Check(result))
438 return TPyReturn(result);
439
440 // explicit conversion for python type required
441 PyObject *pyclass = PyObject_GetAttrString(result, const_cast<char*>("__class__"));
442 if (pyclass != 0) {
443 // retrieve class name and the module in which it resides
444 PyObject *name = PyObject_GetAttr(pyclass, PyStrings::nameStr());
445 PyObject *module = PyObject_GetAttr(pyclass, PyStrings::moduleStr());
446
447 // concat name
448 std::string qname = std::string(PyUnicode_AsUTF8(module)) + '.' + PyUnicode_AsUTF8(name);
449 Py_DECREF(module);
450 Py_DECREF(name);
451 Py_DECREF(pyclass);
452
453 // locate ROOT style class with this name
454 TClass *klass = TClass::GetClass(qname.c_str());
455
456 // construct general ROOT python object that pretends to be of class 'klass'
457 if (klass != 0)
458 return TPyReturn(result);
459 } else
460 PyErr_Clear();
461
462 // no conversion, return null pointer object
463 Py_DECREF(result);
464 return TPyReturn();
465}
466
467////////////////////////////////////////////////////////////////////////////////
468/// Bind a ROOT object with, at the python side, the name "label".
469
470Bool_t TPython::Bind(TObject *object, const char *label)
471{
472 // check given address and setup
473 if (!(object && Initialize()))
474 return kFALSE;
475
476 // bind object in the main namespace
477 TClass *klass = object->IsA();
478 if (klass != 0) {
479 PyObject *bound = CPyCppyy::Instance_FromVoidPtr((void *)object, klass->GetName());
480
481 if (bound) {
482 Bool_t bOk = PyDict_SetItemString(gMainDict, const_cast<char *>(label), bound) == 0;
483 Py_DECREF(bound);
484
485 return bOk;
486 }
487 }
488
489 return kFALSE;
490}
491
492////////////////////////////////////////////////////////////////////////////////
493/// Enter an interactive python session (exit with ^D). State is preserved
494/// between successive calls.
495
497{
498 // setup
499 if (!Initialize()) {
500 return;
501 }
502
503 // enter i/o interactive mode
504 PyRun_InteractiveLoop(stdin, const_cast<char *>("\0"));
505}
506
507////////////////////////////////////////////////////////////////////////////////
508/// Test whether the type of the given pyobject is of CPPInstance type or any
509/// derived type.
510
512{
513 // setup
514 if (!Initialize())
515 return kFALSE;
516
517 // detailed walk through inheritance hierarchy
518 return CPyCppyy::Instance_Check(pyobject);
519}
520
521////////////////////////////////////////////////////////////////////////////////
522/// Test whether the type of the given pyobject is CPPinstance type.
523
525{
526 // setup
527 if (!Initialize())
528 return kFALSE;
529
530 // direct pointer comparison of type member
531 return CPyCppyy::Instance_CheckExact(pyobject);
532}
533
534////////////////////////////////////////////////////////////////////////////////
535/// Test whether the type of the given pyobject is of CPPOverload type or any
536/// derived type.
537
539{
540 // setup
541 if (!Initialize())
542 return kFALSE;
543
544 // detailed walk through inheritance hierarchy
545 return CPyCppyy::Overload_Check(pyobject);
546}
547
548////////////////////////////////////////////////////////////////////////////////
549/// Test whether the type of the given pyobject is CPPOverload type.
550
552{
553 // setup
554 if (!Initialize())
555 return kFALSE;
556
557 // direct pointer comparison of type member
558 return CPyCppyy::Overload_CheckExact(pyobject);
559}
560
561////////////////////////////////////////////////////////////////////////////////
562/// Extract the object pointer held by the CPPInstance pyobject.
563
565{
566 // setup
567 if (!Initialize())
568 return 0;
569
570 // get held object (may be null)
571 return CPyCppyy::Instance_AsVoidPtr(pyobject);
572}
573
574////////////////////////////////////////////////////////////////////////////////
575/// Bind the addr to a python object of class defined by classname.
576
577PyObject *TPython::CPPInstance_FromVoidPtr(void *addr, const char *classname, Bool_t python_owns)
578{
579 // setup
580 if (!Initialize())
581 return 0;
582
583 // perform cast (the call will check TClass and addr, and set python errors)
584 // give ownership, for ref-counting, to the python side, if so requested
585 return CPyCppyy::Instance_FromVoidPtr(addr, classname, python_owns);
586}
#define PyBytes_Check
Definition CPyCppyy.h:61
_object PyObject
RInterface & operator=(const RInterface &)=default
Copy-assignment operator for RInterface.
bool Bool_t
Definition RtypesCore.h:63
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
Int_t i
static PyObject * gMainDict
Definition TPython.cxx:93
#define gROOT
Definition TROOT.h:414
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:2969
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:496
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:538
static void * CPPInstance_AsVoidPtr(PyObject *pyobject)
Extract the object pointer held by the CPPInstance pyobject.
Definition TPython.cxx:564
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:371
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:524
static Bool_t Bind(TObject *object, const char *label)
Bind a ROOT object with, at the python side, the name "label".
Definition TPython.cxx:470
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:551
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:394
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:511
static const TPyReturn Eval(const char *expr)
Evaluate a python expression (e.g.
Definition TPython.cxx:420
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:577
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