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#include <Riostream.h>
25
26// Standard
27#include <mutex>
28#include <sstream>
29#include <stdio.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 TNamed on the python side, and transfer it back and forth.
50/// root [1] std::any res1;
51/// root [2] TPython::Exec("_anyresult = ROOT.std.make_any['TNamed']('hello', '')", &res1);
52/// root [3] TPython::Bind(&std::any_cast<TNamed&>(res1), "n");
53/// root [4] std::any res2;
54/// root [5] TPython::Exec("_anyresult = ROOT.std.make_any['TNamed*', 'TNamed*'](n)", &res2);
55/// root [6] (&std::any_cast<TNamed&>(res1) == std::any_cast<TNamed*>(res2))
56/// (bool) true
57///
58/// // Variables can cross-over by using an `std::any` with a specific name.
59/// root [6] TPython::Exec("_anyresult = ROOT.std.make_any['Int_t'](1 + 1)", &res1);
60/// root [7] std::any_cast<int>(res1)
61/// (int) 2
62/// ~~~
63///
64/// And with a python file `MyPyClass.py` like this:
65/// ~~~{.py}
66/// print 'creating class MyPyClass ... '
67///
68/// class MyPyClass:
69/// def __init__( self ):
70/// print 'in MyPyClass.__init__'
71///
72/// def gime( self, what ):
73/// return what
74/// ~~~
75/// one can load a python module, and use the class. Casts are
76/// necessary as the type information can not be otherwise derived.
77/// ~~~{.cpp}
78/// root [6] TPython::LoadMacro( "MyPyClass.py" );
79/// creating class MyPyClass ...
80/// root [7] MyPyClass m;
81/// in MyPyClass.__init__
82/// root [8] std::string s = (char*)m.gime( "aap" );
83/// root [9] s
84/// (class TString)"aap"
85/// ~~~
86/// It is possible to switch between interpreters by calling `TPython::Prompt()`
87/// on the Cling side, while returning with `^D` (EOF). State is preserved between
88/// successive switches.
89///
90/// The API part provides (direct) C++ access to the bindings functionality of
91/// PyROOT. It allows verifying that you deal with a PyROOT python object in the
92/// first place (CPPInstance_Check for CPPInstance and any derived types, as well
93/// as CPPInstance_CheckExact for CPPInstance's only); and it allows conversions
94/// of `void*` to an CPPInstance and vice versa.
95
96//- data ---------------------------------------------------------------------
98static PyObject *gMainDict = 0;
99
100namespace {
101
103
104// To acquire the GIL as described here:
105// https://docs.python.org/3/c-api/init.html#non-python-created-threads
106class PyGILRAII {
107 PyGILState_STATE m_GILState;
108
109public:
110 PyGILRAII() : m_GILState(PyGILState_Ensure()) {}
111 ~PyGILRAII() { PyGILState_Release(m_GILState); }
112};
113
114struct PyObjDeleter {
115 void operator()(PyObject* obj) const {
116 Py_DecRef(obj);
117 }
118};
119
120using PyObjectRef = std::unique_ptr<PyObject, PyObjDeleter>;
121
122} // namespace
123
124//- static public members ----------------------------------------------------
125/// Initialization method: setup the python interpreter and load the
126/// ROOT module.
128{
129 // Don't initialize Python from two concurrent threads
130 static std::mutex initMutex;
131 const std::lock_guard<std::mutex> lock(initMutex);
132
133 static Bool_t isInitialized = false;
134 if (isInitialized)
135 return true;
136
137 if (!Py_IsInitialized()) {
138 wchar_t rootStr[] = L"root";
139 wchar_t *argv[] = {rootStr};
140 int argc = sizeof(argv) / sizeof(argv[0]);
141#if PY_VERSION_HEX < 0x030b0000
143#else
144 PyStatus status;
145 PyConfig config;
146
148
149 status = PyConfig_SetArgv(&config, argc, argv);
150 if (PyStatus_Exception(status)) {
151 PyConfig_Clear(&config);
152 std::cerr << "Error when setting command line arguments." << std::endl;
153 return false;
154 }
155
156 status = Py_InitializeFromConfig(&config);
157 if (PyStatus_Exception(status)) {
158 PyConfig_Clear(&config);
159 std::cerr << "Error when initializing Python." << std::endl;
160 return false;
161 }
162 PyConfig_Clear(&config);
163#endif
164#if PY_VERSION_HEX < 0x03090000
166#endif
167
168 // try again to see if the interpreter is initialized
169 if (!Py_IsInitialized()) {
170 // give up ...
171 std::cerr << "Error: python has not been intialized; returning." << std::endl;
172 return false;
173 }
174
175#if PY_VERSION_HEX < 0x030b0000
177#endif
178
180 }
181
182 {
183 // For the Python API calls
184 PyGILRAII gilRaii;
185
186 // force loading of the ROOT module
187 const int ret = PyRun_SimpleString("import ROOT");
188 if (ret != 0) {
189 std::cerr << "Error: import ROOT failed, check your PYTHONPATH environmental variable." << std::endl;
190 return false;
191 }
192
193 if (!gMainDict) {
194
195 // retrieve the main dictionary
197 // The gMainDict is borrowed, i.e. we are not calling Py_IncRef(gMainDict).
198 // Like this, we avoid unexpectedly affecting how long __main__ is kept
199 // alive. The gMainDict is only used in Exec(), ExecScript(), and Eval(),
200 // which should not be called after __main__ is garbage collected anyway.
201 }
202 }
203
204 // python side class construction, managed by ROOT
205 gROOT->AddClassGenerator(new TPyClassGenerator);
206
207 // declare success ...
208 isInitialized = true;
209 return true;
210}
211
212////////////////////////////////////////////////////////////////////////////////
213/// Import the named python module and create Cling equivalents for its classes
214/// and methods.
215
217{
218 // setup
219 if (!Initialize())
220 return false;
221
222 PyGILRAII gilRaii;
223
225 return false;
226 }
227
228 // force creation of the module as a namespace
230
234
238
239 // create Cling classes for all new python classes
241 for (int i = 0; i < PyList_Size(values.get()); ++i) {
242 PyObjectRef value{PyList_GetItem(values.get(), i)};
243 Py_IncRef(value.get());
244
245 // collect classes
246 if (PyType_Check(value.get()) || PyObject_HasAttr(value.get(), basesStr.get())) {
247 // get full class name (including module)
249 if (!pyClName) {
250 if (PyErr_Occurred())
251 PyErr_Clear();
253 }
254
255 if (PyErr_Occurred())
256 PyErr_Clear();
257
258 // build full, qualified name
259 std::string fullname = mod_name;
260 fullname += ".";
261 fullname += PyUnicode_AsUTF8AndSize(pyClName.get(), nullptr);
262
263 // force class creation (this will eventually call TPyClassGenerator)
264 TClass::GetClass(fullname.c_str(), true);
265 }
266 }
267
268 return !PyErr_Occurred();
269}
270
271////////////////////////////////////////////////////////////////////////////////
272/// Execute the give python script as if it were a macro (effectively an
273/// execfile in __main__), and create Cling equivalents for any newly available
274/// python classes.
275
276void TPython::LoadMacro(const char *name)
277{
278 // setup
279 if (!Initialize())
280 return;
281
282 PyGILRAII gilRaii;
283
284 // obtain a reference to look for new classes later
286
287// actual execution
288 Exec((std::string("__pyroot_f = open(\"") + name +
289 "\"); "
290 "exec(__pyroot_f.read()); "
291 "__pyroot_f.close(); del __pyroot_f")
292 .c_str());
293
294 // obtain new __main__ contents
296
300
301 // create Cling classes for all new python classes
302 for (int i = 0; i < PyList_Size(current.get()); ++i) {
303 PyObjectRef value{PyList_GetItem(current.get(), i)};
304 Py_IncRef(value.get());
305
306 if (!PySequence_Contains(old.get(), value.get())) {
307 // collect classes
308 if (PyType_Check(value.get()) || PyObject_HasAttr(value.get(), basesStr.get())) {
309 // get full class name (including module)
312
313 if (PyErr_Occurred())
314 PyErr_Clear();
315
316 // need to check for both exact and derived (differences exist between older and newer
317 // versions of python ... bug?)
320 // build full, qualified name
321 std::string fullname = PyUnicode_AsUTF8AndSize(pyModName.get(), nullptr);
322 fullname += '.';
323 fullname += PyUnicode_AsUTF8AndSize(pyClName.get(), nullptr);
324
325 // force class creation (this will eventually call TPyClassGenerator)
326 TClass::GetClass(fullname.c_str(), true);
327 }
328 }
329 }
330 }
331}
332
333////////////////////////////////////////////////////////////////////////////////
334/// Execute a python stand-alone script, with argv CLI arguments.
335///
336/// example of use:
337/// const char* argv[] = { "1", "2", "3" };
338/// TPython::ExecScript( "test.py", sizeof(argv)/sizeof(argv[0]), argv );
339
340void TPython::ExecScript(const char *name, int argc, const char **argv)
341{
342
343 // setup
344 if (!Initialize())
345 return;
346
347 PyGILRAII gilRaii;
348
349 // verify arguments
350 if (!name) {
351 std::cerr << "Error: no file name specified." << std::endl;
352 return;
353 }
354
355 std::vector<std::string> args(argc);
356 for (int i = 0; i < argc; ++i) {
357 args[i] = argv[i];
358 }
360}
361
362////////////////////////////////////////////////////////////////////////////////
363/// Executes a Python command within the current Python environment.
364///
365/// This function initializes the Python environment if it is not already
366/// initialized. It then executes the specified Python command string using the
367/// Python C API.
368///
369/// In the Python command, you can change the value of a special TPyResult
370/// object returned by TPyBuffer(). If the optional result parameter is
371/// non-zero, the result parameter will be swapped with a std::any variable on
372/// the Python side. You need to define this variable yourself, and it needs to
373/// be of type std::any and its name needs to be `"_anyresult"` by default.
374/// Like this, you can pass information from Python back to C++.
375///
376/// \param cmd The Python command to be executed as a string.
377/// \param result Optional pointer to a std::any object that can be used to
378/// transfer results from Python to C++.
379/// \param resultName Name of the Python variable that is swapped over to the std::any result.
380/// The default value is `"_anyresult"`.
381/// \return bool Returns `true` if the command was successfully executed,
382/// otherwise returns `false`.
383
384Bool_t TPython::Exec(const char *cmd, std::any *result, std::string const &resultName)
385{
386 // setup
387 if (!Initialize())
388 return false;
389
390 PyGILRAII gilRaii;
391
392 std::stringstream command;
393 // Add the actual command
394 command << cmd;
395 // Swap the std::any with the one in the C++ world if required
396 if (result) {
397 command << "; ROOT.Internal.SwapWithObjAtAddr['std::any'](" << resultName << ", "
398 << reinterpret_cast<std::intptr_t>(result) << ")";
399 }
400
401 // execute the command
404
405 // test for error
406 if (pyObjectResult) {
407 return true;
408 }
409
410 PyErr_Print();
411 return false;
412}
413
414////////////////////////////////////////////////////////////////////////////////
415/// Bind a ROOT object with, at the python side, the name "label".
416
417Bool_t TPython::Bind(TObject *object, const char *label)
418{
419 // check given address and setup
420 if (!(object && Initialize()))
421 return false;
422
423 PyGILRAII gilRaii;
424
425 // bind object in the main namespace
426 TClass *klass = object->IsA();
427 if (klass != 0) {
428 PyObjectRef bound{CPyCppyy::Instance_FromVoidPtr((void *)object, klass->GetName())};
429
430 if (bound) {
431 Bool_t bOk = PyDict_SetItemString(gMainDict, label, bound.get()) == 0;
432
433 return bOk;
434 }
435 }
436
437 return false;
438}
439
440////////////////////////////////////////////////////////////////////////////////
441/// Enter an interactive python session (exit with ^D). State is preserved
442/// between successive calls.
443
445{
446 // setup
447 if (!Initialize()) {
448 return;
449 }
450
451 PyGILRAII gilRaii;
452
453 // enter i/o interactive mode
455}
456
457////////////////////////////////////////////////////////////////////////////////
458/// Test whether the type of the given pyobject is of CPPInstance type or any
459/// derived type.
460
462{
463 // setup
464 if (!Initialize())
465 return false;
466
467 PyGILRAII gilRaii;
468
469 // detailed walk through inheritance hierarchy
471}
472
473////////////////////////////////////////////////////////////////////////////////
474/// Test whether the type of the given pyobject is CPPinstance type.
475
477{
478 // setup
479 if (!Initialize())
480 return false;
481
482 PyGILRAII gilRaii;
483
484 // direct pointer comparison of type member
486}
487
488////////////////////////////////////////////////////////////////////////////////
489/// Test whether the type of the given pyobject is of CPPOverload type or any
490/// derived type.
491
493{
494 // setup
495 if (!Initialize())
496 return false;
497
498 PyGILRAII gilRaii;
499
500 // detailed walk through inheritance hierarchy
502}
503
504////////////////////////////////////////////////////////////////////////////////
505/// Test whether the type of the given pyobject is CPPOverload type.
506
508{
509 // setup
510 if (!Initialize())
511 return false;
512
513 PyGILRAII gilRaii;
514
515 // direct pointer comparison of type member
517}
518
519////////////////////////////////////////////////////////////////////////////////
520/// Extract the object pointer held by the CPPInstance pyobject.
521
523{
524 // setup
525 if (!Initialize())
526 return nullptr;
527
528 PyGILRAII gilRaii;
529
530 // get held object (may be null)
532}
533
534////////////////////////////////////////////////////////////////////////////////
535/// Bind the addr to a python object of class defined by classname.
536
538{
539 // setup
540 if (!Initialize())
541 return nullptr;
542
543 PyGILRAII gilRaii;
544
545 // perform cast (the call will check TClass and addr, and set python errors)
546 // give ownership, for ref-counting, to the python side, if so requested
548}
_object PyObject
#define ClassImp(name)
Definition Rtypes.h:376
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
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:98
_object PyObject
Definition TPython.h:23
TRObject operator()(const T1 &t1) const
#define gROOT
Definition TROOT.h:411
TClass instances represent classes, structs and namespaces in the ROOT type system.
Definition TClass.h:84
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:2974
Mother of all ROOT objects.
Definition TObject.h:41
Accessing the Python interpreter from C++.
Definition TPython.h:36
static void Prompt()
Enter an interactive python session (exit with ^D).
Definition TPython.cxx:444
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:492
static void * CPPInstance_AsVoidPtr(PyObject *pyobject)
Extract the object pointer held by the CPPInstance pyobject.
Definition TPython.cxx:522
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:340
static Bool_t Import(const char *name)
Import the named python module and create Cling equivalents for its classes and methods.
Definition TPython.cxx:216
static Bool_t CPPInstance_CheckExact(PyObject *pyobject)
Test whether the type of the given pyobject is CPPinstance type.
Definition TPython.cxx:476
static Bool_t Bind(TObject *object, const char *label)
Bind a ROOT object with, at the python side, the name "label".
Definition TPython.cxx:417
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:276
static Bool_t Exec(const char *cmd, std::any *result=nullptr, std::string const &resultName="_anyresult")
Executes a Python command within the current Python environment.
Definition TPython.cxx:384
static Bool_t CPPOverload_CheckExact(PyObject *pyobject)
Test whether the type of the given pyobject is CPPOverload type.
Definition TPython.cxx:507
static Bool_t Initialize()
Initialization method: setup the python interpreter and load the ROOT module.
Definition TPython.cxx:127
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:461
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:537
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