TPython.cxx

Go to the documentation of this file.
00001 // @(#)root/pyroot:$Id: TPython.cxx 35499 2010-09-20 23:04:28Z wlav $
00002 // Author: Wim Lavrijsen, Apr 2004
00003 
00004 // Bindings
00005 #include "PyROOT.h"
00006 #include "PyStrings.h"
00007 #include "TPython.h"
00008 #include "ObjectProxy.h"
00009 #include "RootWrapper.h"
00010 #include "TPyClassGenerator.h"
00011 
00012 // ROOT
00013 #include "TROOT.h"
00014 #include "TObject.h"
00015 
00016 // Standard
00017 #include <stdio.h>
00018 #include <Riostream.h>
00019 #include <string>
00020 
00021 //______________________________________________________________________________
00022 //                          Python interpreter access
00023 //                          =========================
00024 //
00025 // The TPython class allows for access to python objects from CINT. The current
00026 // functionality is only basic: ROOT objects and builtin types can freely cross
00027 // the boundary between the two interpreters, python objects can be instantiated
00028 // and their methods can be called. All other cross-coding is based on strings
00029 // that are run on the python interpreter.
00030 //
00031 // Examples:
00032 //
00033 //  $ cat MyPyClass.py
00034 //  print 'creating class MyPyClass ... '
00035 //
00036 //  class MyPyClass:
00037 //     def __init__( self ):
00038 //        print 'in MyPyClass.__init__'
00039 //
00040 //     def gime( self, what ):
00041 //        return what
00042 //
00043 //  $ root -l
00044 //  // Execute a string of python code.
00045 //  root [0] TPython::Exec( "print \'Hello World!\'" );
00046 //  Hello World!
00047 //
00048 //  // Create a TBrowser on the python side, and transfer it back and forth.
00049 //  // Note the required explicit (void*) cast!
00050 //  root [1] TBrowser* b = (void*)TPython::Eval( "ROOT.TBrowser()" );
00051 //  root [2] TPython::Bind( b, "b" );
00052 //  root [3] b == (void*) TPython::Eval( "b" )
00053 //  (int)1
00054 //
00055 //  // Builtin variables can cross-over by using implicit casts.
00056 //  root [4] int i = TPython::Eval( "1 + 1" );
00057 //  root [5] i
00058 //  (int)2
00059 //
00060 //  // Load a python module with a class definition, and use it.
00061 //  root [6] TPython::LoadMacro( "MyPyClass.py" );
00062 //  creating class MyPyClass ...
00063 //  root [7] MyPyClass m;
00064 //  in MyPyClass.__init__
00065 //  root [8] char* s = m.gime( "aap" );
00066 //  root [9] s
00067 //  (char* 0x41ee7754)"aap"
00068 //
00069 // It is possible to switch between interpreters by calling "TPython::Prompt()"
00070 // on the CINT side, while returning with ^D (EOF). State is preserved between
00071 // successive switches.
00072 //
00073 // The API part provides (direct) C++ access to the bindings functionality of
00074 // PyROOT. It allows verifying that you deal with a PyROOT python object in the
00075 // first place (ObjectProxy_Check for ObjectProxy and any derived types, as well
00076 // as ObjectProxy_CheckExact for ObjectProxy's only); and it allows conversions
00077 // of void* to an ObjectProxy and vice versa.
00078 
00079 
00080 //- data ---------------------------------------------------------------------
00081 ClassImp(TPython)
00082 static PyObject* gMainDict = 0;
00083 
00084 
00085 //- static public members ----------------------------------------------------
00086 Bool_t TPython::Initialize()
00087 {
00088 // Private initialization method: setup the python interpreter and load the
00089 // ROOT module.
00090 
00091    static Bool_t isInitialized = kFALSE;
00092    if ( isInitialized )
00093       return kTRUE;
00094 
00095    if ( ! Py_IsInitialized() ) {
00096    // this happens if CINT comes in first
00097       PyEval_InitThreads();
00098       Py_Initialize();
00099 
00100    // try again to initialize the interpreter
00101       if ( ! Py_IsInitialized() ) {
00102       // give up ...
00103          std::cerr << "Error: python has not been intialized; returning." << std::endl;           
00104          return kFALSE;
00105       }
00106 
00107    // set the command line arguments on python's sys.argv
00108 #if PY_VERSION_HEX < 0x03000000
00109       char* argv[] = { const_cast< char* >( "root" ) };
00110 #else
00111       wchar_t* argv[] = { const_cast< wchar_t* >( L"root" ) };
00112 #endif
00113       PySys_SetArgv( sizeof(argv)/sizeof(argv[0]), argv );
00114 
00115    // force loading of the ROOT module
00116       PyRun_SimpleString( const_cast< char* >( "import ROOT" ) );
00117    }
00118 
00119    if ( ! gMainDict ) {
00120    // retrieve the main dictionary
00121       gMainDict = PyModule_GetDict(
00122          PyImport_AddModule( const_cast< char* >( "__main__" ) ) );
00123       Py_INCREF( gMainDict );
00124    }
00125 
00126 // python side class construction, managed by ROOT
00127    gROOT->AddClassGenerator( new TPyClassGenerator );
00128 
00129 // declare success ...
00130    isInitialized = kTRUE;
00131    return kTRUE;
00132 }
00133 
00134 //____________________________________________________________________________
00135 void TPython::LoadMacro( const char* name )
00136 {
00137 // Execute the give python script as if it were a macro (effectively an
00138 // execfile in __main__), and create CINT equivalents for any newly available
00139 // python classes.
00140 
00141 // setup
00142    if ( ! Initialize() )
00143       return;
00144 
00145 // obtain a reference to look for new classes later
00146    PyObject* old = PyDict_Values( gMainDict );
00147 
00148 // actual execution
00149    Exec( (std::string( "execfile(\"" ) + name + "\")").c_str() );
00150 
00151 // obtain new __main__ contents
00152    PyObject* current = PyDict_Values( gMainDict );
00153 
00154 // create CINT classes for all new python classes
00155    for ( int i = 0; i < PyList_GET_SIZE( current ); ++i ) {
00156       PyObject* value = PyList_GET_ITEM( current, i );
00157       Py_INCREF( value );
00158 
00159       if ( ! PySequence_Contains( old, value ) ) {
00160       // collect classes
00161          if ( PyClass_Check( value ) || PyObject_HasAttr( value, PyROOT::PyStrings::gBases ) ) {
00162          // get full class name (including module)
00163             PyObject* pyModName = PyObject_GetAttr( value, PyROOT::PyStrings::gModule );
00164             PyObject* pyClName  = PyObject_GetAttr( value, PyROOT::PyStrings::gName );
00165 
00166             if ( PyErr_Occurred() )
00167                PyErr_Clear();
00168 
00169          // need to check for both exact and derived (differences exist between older and newer
00170          // versions of python ... bug?)
00171             if ( (pyModName && pyClName) &&\
00172                  ( (PyBytes_CheckExact( pyModName ) && PyBytes_CheckExact( pyClName )) ||\
00173                    (PyBytes_Check( pyModName ) && PyBytes_Check( pyClName ))\
00174                  ) ) {
00175             // build full, qualified name
00176                std::string fullname = PyROOT_PyUnicode_AsString( pyModName );
00177                fullname += '.';
00178                fullname += PyROOT_PyUnicode_AsString( pyClName );
00179 
00180             // force class creation (this will eventually call TPyClassGenerator)
00181                TClass::GetClass( fullname.c_str(), kTRUE );
00182             }
00183 
00184             Py_XDECREF( pyClName );
00185             Py_XDECREF( pyModName );
00186          }
00187       }
00188 
00189       Py_DECREF( value );
00190    }
00191 
00192    Py_DECREF( current );
00193    Py_DECREF( old );
00194 }
00195 
00196 //____________________________________________________________________________
00197 void TPython::ExecScript( const char* name, int argc, const char** argv )
00198 {
00199 // Execute a python stand-alone script, with argv CLI arguments.
00200 //
00201 // example of use:
00202 //    const char* argv[] = { "1", "2", "3" };
00203 //    TPython::ExecScript( "test.py", sizeof(argv)/sizeof(argv[0]), argv );
00204 
00205 
00206 // setup
00207    if ( ! Initialize() )
00208       return;
00209 
00210 // verify arguments
00211    if ( ! name ) {
00212       std::cerr << "Error: no file name specified." << std::endl;
00213       return;
00214    }
00215 
00216    FILE* fp = fopen( name, "r" );
00217    if ( ! fp ) {
00218       std::cerr << "Error: could not open file \"" << name << "\"." << std::endl;
00219       return;
00220    }
00221 
00222 // store a copy of the old cli for restoration
00223    PyObject* oldargv = PySys_GetObject( const_cast< char* >( "argv" ) );   // borrowed
00224    if ( ! oldargv )                               // e.g. apache
00225       PyErr_Clear();
00226    else {
00227       PyObject* l = PyList_New( PyList_GET_SIZE( oldargv ) );
00228       for ( int i = 0; i < PyList_GET_SIZE( oldargv ); ++i ) {
00229          PyObject* item = PyList_GET_ITEM( oldargv, i );
00230          Py_INCREF( item );
00231          PyList_SET_ITEM( l, i, item );           // steals ref
00232       }
00233       oldargv = l;
00234    }
00235 
00236 // create and set (add progam name) the new command line
00237    argc += 1;
00238 #if PY_VERSION_HEX < 0x03000000
00239    const char** argv2 = new const char*[ argc ];
00240    for ( int i = 1; i < argc; ++i ) argv2[ i ] = argv[ i-1 ];
00241    argv2[ 0 ] = Py_GetProgramName();
00242    PySys_SetArgv( argc, const_cast< char** >( argv2 ) );
00243    delete [] argv2;
00244 #else
00245 // TODO: fix this to work like above ...
00246    argv = 0;
00247 #endif
00248 
00249 // actual script execution
00250    PyObject* gbl = PyDict_Copy( gMainDict );
00251    PyObject* result =   // PyRun_FileEx closes fp (b/c of last argument "1")
00252       PyRun_FileEx( fp, const_cast< char* >( name ), Py_file_input, gbl, gbl, 1 );
00253    if ( ! result )
00254       PyErr_Print();
00255    Py_XDECREF( result );
00256    Py_DECREF( gbl );
00257 
00258 // restore original command line
00259    if ( oldargv ) {
00260       PySys_SetObject( const_cast< char* >( "argv" ), oldargv );
00261       Py_DECREF( oldargv );
00262    }
00263 }
00264 
00265 //____________________________________________________________________________
00266 Bool_t TPython::Exec( const char* cmd )
00267 {
00268 // Execute a python statement (e.g. "import ROOT").
00269 
00270 // setup
00271    if ( ! Initialize() )
00272       return kFALSE;
00273 
00274 // execute the command
00275    PyObject* result =
00276       PyRun_String( const_cast< char* >( cmd ), Py_file_input, gMainDict, gMainDict );
00277 
00278 // test for error
00279    if ( result ) {
00280       Py_DECREF( result );
00281       return kTRUE;
00282    } else {
00283       PyErr_Print();
00284       return kFALSE;
00285    }
00286 }
00287 
00288 
00289 //____________________________________________________________________________
00290 const TPyReturn TPython::Eval( const char* expr )
00291 {
00292 // Evaluate a python expression (e.g. "ROOT.TBrowser()").
00293 //
00294 // Caution: do not hold on to the return value: either store it in a builtin
00295 // type (implicit casting will work), or in a pointer to a ROOT object (explicit
00296 // casting to a void* is required).
00297 
00298 // setup
00299    if ( ! Initialize() )
00300       return TPyReturn();
00301 
00302 // evaluate the expression
00303    PyObject* result =
00304       PyRun_String( const_cast< char* >( expr ), Py_eval_input, gMainDict, gMainDict );
00305 
00306 // report errors as appropriate; return void
00307    if ( ! result ) {
00308       PyErr_Print();
00309       return TPyReturn();
00310    }
00311 
00312 // results that require no convserion
00313    if ( result == Py_None || PyROOT::ObjectProxy_Check( result ) ||
00314          PyBytes_Check( result ) ||
00315          PyFloat_Check( result ) || PyLong_Check( result ) || PyInt_Check( result ) )
00316       return TPyReturn( result );
00317 
00318 // explicit conversion for python type required
00319    PyObject* pyclass = PyObject_GetAttr( result, PyROOT::PyStrings::gClass );
00320    if ( pyclass != 0 ) {
00321    // retrieve class name and the module in which it resides
00322       PyObject* name = PyObject_GetAttr( pyclass, PyROOT::PyStrings::gName );
00323       PyObject* module = PyObject_GetAttr( pyclass, PyROOT::PyStrings::gModule );
00324 
00325    // concat name
00326       std::string qname =
00327          std::string( PyROOT_PyUnicode_AsString( module ) ) + '.' + PyROOT_PyUnicode_AsString( name );
00328       Py_DECREF( module );
00329       Py_DECREF( name );
00330       Py_DECREF( pyclass );
00331 
00332    // locate ROOT style class with this name
00333       TClass* klass = TClass::GetClass( qname.c_str() );
00334 
00335    // construct general ROOT python object that pretends to be of class 'klass'
00336       if ( klass != 0 )
00337          return TPyReturn( result );
00338    } else
00339       PyErr_Clear();
00340 
00341 // no conversion, return null pointer object
00342    Py_DECREF( result );
00343    return TPyReturn();
00344 }
00345 
00346 //____________________________________________________________________________
00347 Bool_t TPython::Bind( TObject* object, const char* label )
00348 {
00349 // Bind a ROOT object with, at the python side, the name "label".
00350 
00351 // check given address and setup
00352    if ( ! ( object && Initialize() ) )
00353       return kFALSE;
00354 
00355 // bind object in the main namespace
00356    TClass* klass = object->IsA();
00357    if ( klass != 0 ) {
00358       PyObject* bound = PyROOT::BindRootObject( (void*)object, klass );
00359 
00360       if ( bound ) {
00361          Bool_t bOk = PyDict_SetItemString( gMainDict, const_cast< char* >( label ), bound ) == 0;
00362          Py_DECREF( bound );
00363 
00364          return bOk;
00365       }
00366    }
00367 
00368    return kFALSE;
00369 }
00370 
00371 //____________________________________________________________________________
00372 void TPython::Prompt() {
00373 // Enter an interactive python session (exit with ^D). State is preserved
00374 // between successive calls.
00375 
00376 // setup
00377    if ( ! Initialize() ) {
00378       return;
00379    }
00380 
00381 // enter i/o interactive mode
00382    PyRun_InteractiveLoop( stdin, const_cast< char* >( "\0" ) );
00383 }
00384 
00385 //____________________________________________________________________________
00386 Bool_t TPython::ObjectProxy_Check( PyObject* pyobject )
00387 {
00388 // Test whether the type of the given pyobject is of ObjectProxy type or any
00389 // derived type.
00390 
00391 // setup
00392    if ( ! Initialize() )
00393       return kFALSE;
00394 
00395 // detailed walk through inheritance hierarchy
00396    return PyROOT::ObjectProxy_Check( pyobject );
00397 }
00398 
00399 //____________________________________________________________________________
00400 Bool_t TPython::ObjectProxy_CheckExact( PyObject* pyobject )
00401 {
00402 // Test whether the type of the given pyobject is ObjectProxy type.
00403 
00404 // setup
00405    if ( ! Initialize() )
00406       return kFALSE;
00407 
00408 // direct pointer comparison of type member
00409    return PyROOT::ObjectProxy_CheckExact( pyobject );
00410 }
00411 
00412 //____________________________________________________________________________
00413 void* TPython::ObjectProxy_AsVoidPtr( PyObject* pyobject )
00414 {
00415 // Extract the object pointer held by the ObjectProxy pyobject.
00416 
00417 // setup
00418    if ( ! Initialize() )
00419       return 0;
00420 
00421 // check validity of cast
00422    if ( ! PyROOT::ObjectProxy_Check( pyobject ) )
00423       return 0;
00424 
00425 // get held object (may be null)
00426    return ((PyROOT::ObjectProxy*)pyobject)->GetObject();
00427 }
00428 
00429 //____________________________________________________________________________
00430 PyObject* TPython::ObjectProxy_FromVoidPtr( void* addr, const char* classname )
00431 {
00432 // Bind the addr to a python object of class defined by classname.
00433 
00434 // setup
00435    if ( ! Initialize() )
00436       return 0;
00437 
00438 // perform cast (the call will check TClass and addr, and set python errors)
00439    return PyROOT::BindRootObjectNoCast( addr, TClass::GetClass( classname ), kFALSE );
00440 }

Generated on Tue Jul 5 14:10:16 2011 for ROOT_528-00b_version by  doxygen 1.5.1