You are here

How to Use PyROOT, the ROOT Python Bindings?

PyROOT is a Python extension module that allows the user to interact with any ROOT class from the Python interpreter. This is done generically interrogating the ROOT type system, therefore there is no need to generate any Python wrapper code to include new ROOT classes. At the same time PyROOT offers the possibility to execute and evaluate any Python command or start a Python shell from the ROOT/Cling prompt. Further details are available in the PyROOT manual.

How to Build and Install PyROOT

The user should follow the standard ROOT installation instructions and, if necessary, enable the build of the PyROOT module. A Python version > 2.2 is required, the location of needs to be specified if it is not installed in any of the standard places: see the build instructions for more details. A library called will be created in the $ROOTSYS/lib and a top Python module will be copied to the same place.

Running PyROOT from the Python Interpreter

The user should make sure that the python command is the one of the installation that has been used to build the PyROOT extension module. The top level Python module is This module imports the extension module (.dll) and does a similar initialization as the ROOT application (i.e. loading common libraries, defining a number of globals, starting a thread to handle GUI events, etc.). This is the main entry point for any Python script using the ROOT classes. An example is as follows:

from ROOT import TCanvas, TF1

c1 = TCanvas( 'c1', 'Example with Formula', 200, 10, 700, 500 )

# Create a one dimensional function and draw it
fun1 = TF1( 'fun1', 'abs(sin(x)/x)', 0, 10 )

The user can find a number of examples in $ROOTSYS/tutorials/pyroot. To run them, simply execute the command

python $ROOTSYS/tutorials/pyroot/

Running Python from ROOT/Cling Interpreter

A ROOT user can run any Python command and eventually switch to the python prompt from the ROOT/Cling prompt; the interpreter state will be preserved in between calls. Example commands to execute are:

root [0] TPython::Exec( "print 1 + 1" )
root [1] auto b = (TBrowser*)TPython::Eval( "ROOT.TBrowser()" )
(class TObject*)0x8d1daa0
root [2] TPython::Prompt()
>>> i = 2^D
root [3] TPython::Prompt()
>>> print i

Interplay between Python and C++ via the PyROOT bindings (ROOT6 only)

As mentioned above, it is possible to interact with C++ classes present in the ROOT type system without the need of generating Python bindings for them. This feature becomes particularly attractive in presence of classes and other entities made known to ROOT only at runtime, for example:

>>> import ROOT
>>> code="""
... class myClass {
... public:
...   myClass(){cout << "Jit and automatic bindings rock!" << endl;}
... };
... """
>>> ROOT.gInterpreter.ProcessLine(code)
>>> a=ROOT.A()
>>> myObj=ROOT.myClass()
Jit and automatic bindings rock!