Python Interface

Python is a popular scripting language with an interactive interpreter. Geant4Py, a Geant4-Python bridge, provides a bridge for Geant4 classes. This enables to directly access Geant4 classes from Python scripting. User applications can be easily configured with many Python third-party modules, such as PyROOT, on the Python software bus.

Geant4Py is supplied in the directory environments/g4py/ of the Geant4 source package and can be built/installed together with the core C++ libraries.

Note that Geant4Py only supports Python 3 and newer.

Using Geant4Py

The Geant4 python package is installed by default under <Geant4InstallPrefix>/lib{64}/python3.<PYMINOR>/site-packages, where <Geant4InstallPrefix> is the path under which you installed Geant4, and <PYMINOR> is the minor version of Python the bindings were built against. If the path to the Geant4 package is not known to Python, it should be appended to the PYTHONPATH environment variable.

Before running Python and importing Geant4, you should also ensure that the environment variables for the Geant4 data libraries are set otherwise you will see errors on import Geant4.

Import Geant4

To use Geant4Py, you start with importing the module called “Geant4”.

# python
...
>>> from Geant4 import *

Access to Geant4 Globals

When importing the Geant4 module, the G4RunManager object will be automatically instantiated. Geant4 singleton objects are also automatically instantiated. These singleton objects can be accessed by “gXXXX” variables, like “gRunManager”.

.                       gLossTableManager       gTerminate
gApplyUICommand         gMaterialTable          gTrackingManager
gControlExecute         gNistManager            gTransportationManager
gElementTable           gParticleIterator       gUImanager
gEmCalculator           gParticleTable          gVisManager
gEventManager           gProcessTable
gExceptionHandler       gProductionCutsTable
gG4Date                 gRunManager
gG4VERSION_NUMBER       gRunManagerKernel
gG4Version              gStackManager
gGeometryManager        gStartUISession
gGetCurrentValues       gStateManager

Call Geant4 Methods

Once a Python object of a Geant4 class instantiated, Geant4 methods can be directly called the same way as in C++.

>>> from Geant4 import *
>>> print gRunManager.GetVersionString()

Developing Geant4Py

A new set of examples and further documentation are under preparation for Geant4Py at this time. We welcome questions, comments, suggestions for improvement, and example use cases on our Discourse Forum.