Search code examples
pythonroot-framework

How does PyROOT change the python interpreter?


If I try to run .ls in python, not surprisingly I get a SyntaxError

>>> .ls
  File "<stdin>", line 1
    .ls
    ^
SyntaxError: invalid syntax

But if I import PyROOT, it somehow makes this syntax legal (and behaves as it does in ROOT, listing the contents of the current file; in the example here I haven't opened any.)

>>> import ROOT
>>> .ls
>>>

Similarly, .q works to quit the Python interpreter after I've imported ROOT, as it does in the normal ROOT interpreter.

How does this work?


Solution

  • It can by found in lib/ROOT.py

    there is condition that if not ipython the sys.excepthook is redefined:

    sys.excepthook = _excepthook
    

    which in turn contains stuff like:

    ### RINT command emulation     
    ------------------------------------------------------
    def _excepthook( exctype, value, traceb ):
     # catch syntax errors only (they contain the full line)
       if isinstance( value, SyntaxError ) and value.text:
          cmd, arg = split( value.text[:-1] )
    
        # mimic ROOT/CINT commands
          if cmd == '.q':
             sys.exit( 0 )
    

    or few lines bellow:

      elif cmd == '.ls':
         return sys.modules[ __name__ ].gDirectory.ls()
    

    and if non of those work it resumes normal handling of things.