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