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