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 ---------------------------------------------------------------------
97static PyObject *gMainDict = 0;
98
99namespace {
100
102
103// To acquire the GIL as described here:
104// https://docs.python.org/3/c-api/init.html#non-python-created-threads
105class PyGILRAII {
106 PyGILState_STATE m_GILState;
107
108public:
109 PyGILRAII() : m_GILState(PyGILState_Ensure()) {}
110 ~PyGILRAII() { PyGILState_Release(m_GILState); }
111};
112
113struct PyObjDeleter {
114 void operator()(PyObject* obj) const {
115 Py_DecRef(obj);
116 }
117};
118
119using PyObjectRef = std::unique_ptr<PyObject, PyObjDeleter>;
120
121} // namespace
122
123//- static public members ----------------------------------------------------
124/// Initialization method: setup the python interpreter and load the
125/// ROOT module.
127{
128 // Don't initialize Python from two concurrent threads
129 static std::mutex initMutex;
130 const std::lock_guard<std::mutex> lock(initMutex);
131
132 static Bool_t isInitialized = false;
133 if (isInitialized)
134 return true;
135
136 if (!Py_IsInitialized()) {
137 wchar_t rootStr[] = L"root";
138 wchar_t *argv[] = {rootStr};
139 int argc = sizeof(argv) / sizeof(argv[0]);
140#if PY_VERSION_HEX < 0x030b0000
142#else
143 PyStatus status;
144 PyConfig config;
145
147
148 status = PyConfig_SetArgv(&config, argc, argv);
149 if (PyStatus_Exception(status)) {
150 PyConfig_Clear(&config);
151 std::cerr << "Error when setting command line arguments." << std::endl;
152 return false;
153 }
154
155 status = Py_InitializeFromConfig(&config);
156 if (PyStatus_Exception(status)) {
157 PyConfig_Clear(&config);
158 std::cerr << "Error when initializing Python." << std::endl;
159 return false;
160 }
161 PyConfig_Clear(&config);
162#endif
163
164 // try again to see if the interpreter is initialized
165 if (!Py_IsInitialized()) {
166 // give up ...
167 std::cerr << "Error: python has not been intialized; returning." << std::endl;
168 return false;
169 }
170
171#if PY_VERSION_HEX < 0x030b0000
173#endif
174
176 }
177
178 {
179 // For the Python API calls
180 PyGILRAII gilRaii;
181
182 // force loading of the ROOT module
183 const int ret = PyRun_SimpleString("import ROOT");
184 if (ret != 0) {
185 std::cerr << "Error: import ROOT failed, check your PYTHONPATH environmental variable." << std::endl;
186 return false;
187 }
188 // to trigger the lazy initialization of the C++ runtime
189 if (PyRun_SimpleString("ROOT.gInterpreter") != 0) {
190 std::cerr << "Error: initializing ROOT Python module failed." << std::endl;
191 return false;
192 }
193
194 if (!gMainDict) {
195
196 // retrieve the main dictionary
198 // The gMainDict is borrowed, i.e. we are not calling Py_IncRef(gMainDict).
199 // Like this, we avoid unexpectedly affecting how long __main__ is kept
200 // alive. The gMainDict is only used in Exec(), ExecScript(), and Eval(),
201 // which should not be called after __main__ is garbage collected anyway.
202 }
203 }
204
205 // python side class construction, managed by ROOT
206 gROOT->AddClassGenerator(new TPyClassGenerator);
207
208 // declare success ...
209 isInitialized = true;
210 return true;
211}
212
213////////////////////////////////////////////////////////////////////////////////
214/// Import the named python module and create Cling equivalents for its classes
215/// and methods.
216
218{
219 // setup
220 if (!Initialize())
221 return false;
222
223 PyGILRAII gilRaii;
224
226 return false;
227 }
228
229 // force creation of the module as a namespace
231
235
239
240 // create Cling classes for all new python classes
242 for (int i = 0; i < PyList_Size(values.get()); ++i) {
243 PyObjectRef value{PyList_GetItem(values.get(), i)};
244 Py_IncRef(value.get());
245
246 // collect classes
247 if (PyType_Check(value.get()) || PyObject_HasAttr(value.get(), basesStr.get())) {
248 // get full class name (including module)
250 if (!pyClName) {
251 if (PyErr_Occurred())
252 PyErr_Clear();
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_AsUTF8AndSize(pyClName.get(), nullptr);
263
264 // force class creation (this will eventually call TPyClassGenerator)
265 TClass::GetClass(fullname.c_str(), true);
266 }
267 }
268
269 return !PyErr_Occurred();
270}
271
272////////////////////////////////////////////////////////////////////////////////
273/// Execute the give python script as if it were a macro (effectively an
274/// execfile in __main__), and create Cling equivalents for any newly available
275/// python classes.
276
277void TPython::LoadMacro(const char *name)
278{
279 // setup
280 if (!Initialize())
281 return;
282
283 PyGILRAII gilRaii;
284
285 // obtain a reference to look for new classes later
287
288// actual execution
289 Exec((std::string("__pyroot_f = open(\"") + name +
290 "\"); "
291 "exec(__pyroot_f.read()); "
292 "__pyroot_f.close(); del __pyroot_f")
293 .c_str());
294
295 // obtain new __main__ contents
297
301
302 // create Cling classes for all new python classes
303 for (int i = 0; i < PyList_Size(current.get()); ++i) {
304 PyObjectRef value{PyList_GetItem(current.get(), i)};
305 Py_IncRef(value.get());
306
307 if (!PySequence_Contains(old.get(), value.get())) {
308 // collect classes
309 if (PyType_Check(value.get()) || PyObject_HasAttr(value.get(), basesStr.get())) {
310 // get full class name (including module)
313
314 if (PyErr_Occurred())
315 PyErr_Clear();
316
317 // need to check for both exact and derived (differences exist between older and newer
318 // versions of python ... bug?)
321 // build full, qualified name
322 std::string fullname = PyUnicode_AsUTF8AndSize(pyModName.get(), nullptr);
323 fullname += '.';
324 fullname += PyUnicode_AsUTF8AndSize(pyClName.get(), nullptr);
325
326 // force class creation (this will eventually call TPyClassGenerator)
327 TClass::GetClass(fullname.c_str(), true);
328 }
329 }
330 }
331 }
332}
333
334////////////////////////////////////////////////////////////////////////////////
335/// Execute a python stand-alone script, with argv CLI arguments.
336///
337/// example of use:
338/// const char* argv[] = { "1", "2", "3" };
339/// TPython::ExecScript( "test.py", sizeof(argv)/sizeof(argv[0]), argv );
340
341void TPython::ExecScript(const char *name, int argc, const char **argv)
342{
343
344 // setup
345 if (!Initialize())
346 return;
347
348 PyGILRAII gilRaii;
349
350 // verify arguments
351 if (!name) {
352 std::cerr << "Error: no file name specified." << std::endl;
353 return;
354 }
355
356 std::vector<std::string> args(argc);
357 for (int i = 0; i < argc; ++i) {
358 args[i] = argv[i];
359 }
361}
362
363////////////////////////////////////////////////////////////////////////////////
364/// Executes a Python command within the current Python environment.
365///
366/// This function initializes the Python environment if it is not already
367/// initialized. It then executes the specified Python command string using the
368/// Python C API.
369///
370/// In the Python command, you can change the value of a special TPyResult
371/// object returned by TPyBuffer(). If the optional result parameter is
372/// non-zero, the result parameter will be swapped with a std::any variable on
373/// the Python side. You need to define this variable yourself, and it needs to
374/// be of type std::any and its name needs to be `"_anyresult"` by default.
375/// Like this, you can pass information from Python back to C++.
376///
377/// \param cmd The Python command to be executed as a string.
378/// \param result Optional pointer to a std::any object that can be used to
379/// transfer results from Python to C++.
380/// \param resultName Name of the Python variable that is swapped over to the std::any result.
381/// The default value is `"_anyresult"`.
382/// \return bool Returns `true` if the command was successfully executed,
383/// otherwise returns `false`.
384
385Bool_t TPython::Exec(const char *cmd, std::any *result, std::string const &resultName)
386{
387 // setup
388 if (!Initialize())
389 return false;
390
391 PyGILRAII gilRaii;
392
393 std::stringstream command;
394 // Add the actual command
395 command << cmd;
396 // Swap the std::any with the one in the C++ world if required
397 if (result) {
398 command << "; ROOT.Internal.SwapWithObjAtAddr['std::any'](" << resultName << ", "
399 << reinterpret_cast<std::intptr_t>(result) << ")";
400 }
401
402 // execute the command
405
406 // test for error
407 if (pyObjectResult) {
408 return true;
409 }
410
411 PyErr_Print();
412 return false;
413}
414
415////////////////////////////////////////////////////////////////////////////////
416/// Bind a ROOT object with, at the python side, the name "label".
417
418Bool_t TPython::Bind(TObject *object, const char *label)
419{
420 // check given address and setup
421 if (!(object && Initialize()))
422 return false;
423
424 PyGILRAII gilRaii;
425
426 // bind object in the main namespace
427 TClass *klass = object->IsA();
428 if (klass != 0) {
429 PyObjectRef bound{CPyCppyy::Instance_FromVoidPtr((void *)object, klass->GetName())};
430
431 if (bound) {
432 Bool_t bOk = PyDict_SetItemString(gMainDict, label, bound.get()) == 0;
433
434 return bOk;
435 }
436 }
437
438 return false;
439}
440
441////////////////////////////////////////////////////////////////////////////////
442/// Enter an interactive python session (exit with ^D). State is preserved
443/// between successive calls.
444
446{
447 // setup
448 if (!Initialize()) {
449 return;
450 }
451
452 PyGILRAII gilRaii;
453
454 // enter i/o interactive mode
456}
457
458////////////////////////////////////////////////////////////////////////////////
459/// Test whether the type of the given pyobject is of CPPInstance type or any
460/// derived type.
461
463{
464 // setup
465 if (!Initialize())
466 return false;
467
468 PyGILRAII gilRaii;
469
470 // detailed walk through inheritance hierarchy
472}
473
474////////////////////////////////////////////////////////////////////////////////
475/// Test whether the type of the given pyobject is CPPinstance type.
476
478{
479 // setup
480 if (!Initialize())
481 return false;
482
483 PyGILRAII gilRaii;
484
485 // direct pointer comparison of type member
487}
488
489////////////////////////////////////////////////////////////////////////////////
490/// Test whether the type of the given pyobject is of CPPOverload type or any
491/// derived type.
492
494{
495 // setup
496 if (!Initialize())
497 return false;
498
499 PyGILRAII gilRaii;
500
501 // detailed walk through inheritance hierarchy
503}
504
505////////////////////////////////////////////////////////////////////////////////
506/// Test whether the type of the given pyobject is CPPOverload type.
507
509{
510 // setup
511 if (!Initialize())
512 return false;
513
514 PyGILRAII gilRaii;
515
516 // direct pointer comparison of type member
518}
519
520////////////////////////////////////////////////////////////////////////////////
521/// Extract the object pointer held by the CPPInstance pyobject.
522
524{
525 // setup
526 if (!Initialize())
527 return nullptr;
528
529 PyGILRAII gilRaii;
530
531 // get held object (may be null)
533}
534
535////////////////////////////////////////////////////////////////////////////////
536/// Bind the addr to a python object of class defined by classname.
537
539{
540 // setup
541 if (!Initialize())
542 return nullptr;
543
544 PyGILRAII gilRaii;
545
546 // perform cast (the call will check TClass and addr, and set python errors)
547 // give ownership, for ref-counting, to the python side, if so requested
549}
_object PyObject
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:97
_object PyObject
Definition TPython.h:23
TRObject operator()(const T1 &t1) const
#define gROOT
Definition TROOT.h:414
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:2973
Mother of all ROOT objects.
Definition TObject.h:42
static void Prompt()
Enter an interactive python session (exit with ^D).
Definition TPython.cxx:445
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:493
static void * CPPInstance_AsVoidPtr(PyObject *pyobject)
Extract the object pointer held by the CPPInstance pyobject.
Definition TPython.cxx:523
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:341
static Bool_t Import(const char *name)
Import the named python module and create Cling equivalents for its classes and methods.
Definition TPython.cxx:217
static Bool_t CPPInstance_CheckExact(PyObject *pyobject)
Test whether the type of the given pyobject is CPPinstance type.
Definition TPython.cxx:477
static Bool_t Bind(TObject *object, const char *label)
Bind a ROOT object with, at the python side, the name "label".
Definition TPython.cxx:418
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:277
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:385
static Bool_t CPPOverload_CheckExact(PyObject *pyobject)
Test whether the type of the given pyobject is CPPOverload type.
Definition TPython.cxx:508
static Bool_t Initialize()
Initialization method: setup the python interpreter and load the ROOT module.
Definition TPython.cxx:126
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:462
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:538
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