1 from __future__
import generators
9 o) install lazy ROOT class/variable lookup as appropriate
10 o) feed gSystem and gInterpreter for display updates
11 o) add readline completion (if supported by python build)
12 o) enable some ROOT/Cling style commands
13 o) handle a few special cases such as gPad, STL, etc.
14 o) execute rootlogon.py/.C scripts
19 __author__ =
'Wim Lavrijsen (WLavrijsen@lbl.gov)'
27 if sys.version[0:3] <
'2.2':
28 raise ImportError(
'Python Version 2.2 or above is required.' )
31 if sys.version[0:3] ==
'2.2':
32 sys.setcheckinterval( 100 )
36 import rlcompleter, readline
41 path, name = os.path.split( text )
44 for fn
in os.listdir( path
or os.curdir ):
45 if fn[:len(name)] == name:
46 full = os.path.join( path, fn )
47 matches.append( full )
49 if os.path.isdir( full ):
50 matches += map(
lambda x: os.path.join( full, x ), os.listdir( full ) )
57 gClassTable = _root.GetCppGlobal(
'gClassTable' )
58 all = [ gClassTable.At(i)
for i
in xrange(gClassTable.Classes()) ]
59 all += [ g.GetName()
for g
in _root.gROOT.GetListOfGlobals() ]
60 matches = filter(
lambda x: x[:len(text)] == text, all )
61 return [prefix + x
for x
in matches]
64 matches = rlcompleter.Completer.global_matches( self, text )
65 if not matches: matches = []
70 matches = rlcompleter.Completer.attr_matches( self, text )
71 if not matches: matches = []
74 if 0 <= b
and self.namespace[text[:b]].__name__ ==
'ROOT':
76 except AttributeError:
81 readline.set_completer_delims(
82 readline.get_completer_delims().replace( os.sep ,
'' ) )
84 readline.parse_and_bind(
'tab: complete' )
85 readline.parse_and_bind(
'set show-all-if-ambiguous On' )
91 if sys.platform ==
'darwin':
93 warnings.filterwarnings( action=
'ignore', category=RuntimeWarning, module=
'ROOT',\
94 message=
'class \S* already in TClassTable$' )
97 _root = cppyy._backend
100 if sys.version[0:3] ==
'2.2':
102 copy_reg.constructor( _root._ObjectProxy__expand__ )
108 inspect._old_isfunction = inspect.isfunction
110 if type(object) == _root.MethodProxy
and not object.im_class:
112 return inspect._old_isfunction( object )
113 inspect.isfunction = isfunction
115 inspect._old_ismethod = inspect.ismethod
117 if type(object) == _root.MethodProxy:
119 return inspect._old_ismethod( object )
120 inspect.ismethod = ismethod
122 del isfunction, ismethod
127 __slots__ = [
'IgnoreCommandLineOptions',
'StartGuiThread',
'ExposeCppMacros',
128 '_gts',
'DisableRootLogon' ]
139 if not callable( c ):
140 raise ValueError(
'"%s" is not callable' % str(c) );
146 GUIThreadScheduleOnce = property( __getGTS, __setGTS )
153 _root.SetMemoryPolicy( _root.kMemoryHeuristics )
154 _root.SetSignalPolicy( _root.kSignalSafe )
158 __pseudo__all__ = [
'gROOT',
'gSystem',
'gInterpreter',
159 'AddressOf',
'MakeNullPointer',
'Template',
'std' ]
162 _orig_ehook = sys.excepthook
165 _memPolicyAPI = [
'SetMemoryPolicy',
'SetOwnership',
'kMemoryHeuristics',
'kMemoryStrict' ]
166 _sigPolicyAPI = [
'SetSignalPolicy',
'kSignalFast',
'kSignalSafe' ]
171 npos = str.find(
' ' )
173 return str[:npos], str[npos+1:]
179 _root.std = cppyy.gbl.std
180 sys.modules[
'ROOT.std'] = cppyy.gbl.std
186 c = _root.CreateScopeProxy( klass )
190 return getattr( self.__dict__[
'func' ](), what )
193 return cmp( self.
func(), other )
201 return repr( self.
func() )
204 return str( self.
func() )
216 bytes_read = self.GetEntry(i)
217 while 0 < bytes_read:
220 bytes_read = self.GetEntry(i)
223 raise RuntimeError(
"TTree I/O error" )
225 _root.CreateScopeProxy(
"TTree" ).__iter__ = _TTree__iter__
231 if isinstance( value, SyntaxError )
and value.text:
232 cmd, arg =
split( value.text[:-1] )
237 elif cmd ==
'.?' or cmd ==
'.help':
238 sys.stdout.write(
"""PyROOT emulation of Cling commands.
239 All emulated commands must be preceded by a . (dot).
240 ===========================================================================
243 Shell: ![shell] : execute shell command
244 Evaluation: x [file] : load [file] and evaluate {statements} in the file
245 Load/Unload: L [lib] : load [lib]
246 Quit: q : quit python session
248 The standard python help system is available through a call to 'help()' or
249 'help(<id>)' where <id> is an identifier, e.g. a class or function such as
250 TPad or TPad.cd, etc.
253 elif cmd ==
'.!' and arg:
254 return os.system( arg )
255 elif cmd ==
'.x' and arg:
257 fn = os.path.expanduser( os.path.expandvars( arg ) )
258 execfile( fn, __main__.__dict__, __main__.__dict__ )
261 return _root.gSystem.Load( arg )
262 elif cmd ==
'.cd' and arg:
266 return sys.modules[ __name__ ].gDirectory.ls()
268 return sys.modules[ __name__ ].gDirectory.pwd()
269 elif isinstance( value, SyntaxError )
and \
270 value.msg ==
"can't assign to function call":
271 sys.stdout.write(
"""Are you trying to assign a value to a reference return, for example to the
272 result of a call to "double& SMatrix<>::operator()(int,int)"? If so, then
273 please use operator[] instead, as in e.g. "mymatrix[i][j] = somevalue".
279 if not '__IPYTHON__' in __builtins__:
281 sys.excepthook = _excepthook
285 _orig_dhook = sys.displayhook
287 _root.gInterpreter.EndOfLineAction()
295 import builtins
as __builtin__
296 _orig_ihook = __builtin__.__import__
298 if name[0:5] ==
'ROOT.':
300 sys.modules[ name ] = getattr( sys.modules[
'ROOT' ], name[5:] )
305 __builtin__.__import__ = _importhook
311 gSystemProcessEvents = _root.gSystem.ProcessEvents
313 if sys.platform ==
'win32':
315 _root.gROOT.ProcessLineSync(
'((TGWin32 *)gVirtualX)->SetUserThreadId(%ld)' % (thread.get_ident()))
317 while controller.keeppolling:
319 gSystemProcessEvents()
320 if PyConfig.GUIThreadScheduleOnce:
321 for guicall
in PyConfig.GUIThreadScheduleOnce:
323 PyConfig.GUIThreadScheduleOnce = []
332 types.ModuleType.__init__( self,
'ROOT' )
334 self.__dict__[
'module' ] = module
336 self.__dict__[
'__doc__' ] = self.module.__doc__
337 self.__dict__[
'__name__' ] = self.module.__name__
338 self.__dict__[
'__file__' ] = self.module.__file__
340 self.__dict__[
'keeppolling' ] = 0
341 self.__dict__[
'PyConfig' ] = self.module.PyConfig
343 class gROOTWrapper( object ):
344 def __init__( self, gROOT, master ):
345 self.__dict__[
'_master' ] = master
346 self.__dict__[
'_gROOT' ] = gROOT
348 def __getattr__( self, name ):
349 if name !=
'SetBatch' and self._master.__dict__[
'gROOT' ] != self._gROOT:
350 self._master._ModuleFacade__finalSetup()
351 del self._master.__class__._ModuleFacade__finalSetup
352 return getattr( self._gROOT, name )
354 def __setattr__( self, name, value ):
355 return setattr( self._gROOT, name, value )
357 self.__dict__[
'gROOT' ] = gROOTWrapper( _root.gROOT, self )
361 self.__class__.__getattr__ = self.__class__.__getattr1
362 del self.__class__.__getattr1
363 self.__class__.__setattr__ = self.__class__.__setattr1
364 del self.__class__.__setattr1
369 del self.__class__.__finalSetup
372 return setattr( self, name, value )
376 if not name
in self.__dict__:
379 setattr( self.__class__, name, _root.GetCppGlobal( name ) )
382 if sys.hexversion >= 0x3000000:
386 tcnv = { bool :
'bool %s = %d;',
387 int :
'int %s = %d;',
388 pylong :
'long %s = %d;',
389 float :
'double %s = %f;',
390 str :
'string %s = "%s";' }
392 _root.gROOT.ProcessLine( tcnv[
type(value) ] % (name,value) );
393 setattr( self.__class__, name, _root.GetCppGlobal( name ) )
398 return super( self.__class__, self ).__setattr__( name, value )
402 if name ==
'__path__':
403 raise AttributeError( name )
407 del self.__class__.__finalSetup
410 return getattr( self, name )
414 if name ==
'__all__':
415 if '__IPYTHON__' in __builtins__:
417 warnings.warn(
'"from ROOT import *" is not supported under IPython' )
420 caller = sys.modules[ sys._getframe( 1 ).f_globals[
'__name__' ] ]
424 caller = sys.modules[ sys._getframe( 2 ).f_globals[
'__name__' ] ]
427 for name
in self.module.__pseudo__all__:
428 caller.__dict__[ name ] = getattr( _root, name )
431 _root.SetRootLazyLookup( caller.__dict__ )
434 return self.module.__all__
438 attr = _root.LookupCppEntity( name, PyConfig.ExposeCppMacros )
439 if type(attr) == _root.PropertyProxy:
440 setattr( self.__class__, name, attr )
441 return getattr( self, name )
443 self.__dict__[ name ] = attr
445 except AttributeError:
449 raise AttributeError( name )
454 delattr( self.module._root, name )
455 except AttributeError:
458 return super( self.__class__, self ).
__delattr__( name )
462 self.__dict__[
'gROOT' ] = _root.gROOT
465 self.__class__.__getattr__ = self.__class__.__getattr2
466 del self.__class__.__getattr2
467 self.__class__.__setattr__ = self.__class__.__setattr2
468 del self.__class__.__setattr2
472 hasargv = hasattr( sys,
'argv' )
473 if hasargv
and PyConfig.IgnoreCommandLineOptions:
477 appc = _root.CreateScopeProxy(
'PyROOT::TPyROOTApplication' )
478 if appc.CreatePyROOTApplication():
479 appc.InitROOTGlobals()
481 appc.InitROOTMessageCallback();
483 if hasargv
and PyConfig.IgnoreCommandLineOptions:
487 if '__IPYTHON__' in __builtins__:
489 _root.gROOT.ProcessLine(
'TPython::Exec( "" );' )
490 sys.modules[
'__main__' ].__builtins__ = __builtins__
493 if hasattr( cppyy.gbl.std,
'__1' ):
494 attr_1 = getattr( cppyy.gbl.std,
'__1' )
495 if hasattr( attr_1,
'cout' ):
496 self.__dict__[
'cout' ] = attr_1.cout
499 if hasargv
and not '-n' in sys.argv
and not PyConfig.DisableRootLogon:
500 rootlogon = os.path.expanduser(
'~/.rootlogon.py' )
501 if os.path.exists( rootlogon ):
504 imp.load_module(
'rootlogon',
open( rootlogon,
'r' ), rootlogon, ('.py','
r',1) )
510 name =
'.rootlogon.C'
511 logons = [ os.path.join( str(self.gRootDir),
'etc',
'system' + name ),
512 os.path.expanduser( os.path.join(
'~', name ) ) ]
513 if logons[-1] != os.path.join( os.getcwd(), name ):
514 logons.append( name )
515 for rootlogon
in logons:
516 if os.path.exists( rootlogon ):
517 appc.ExecuteFile( rootlogon )
518 del rootlogon, logons
521 if self.PyConfig.StartGuiThread
and \
522 not ( self.keeppolling
or _root.gROOT.IsBatch() ):
523 if self.PyConfig.StartGuiThread ==
'inputhook' or\
524 _root.gSystem.InheritsFrom(
'TMacOSXSystem' ):
526 if PyConfig.GUIThreadScheduleOnce:
527 for guicall
in PyConfig.GUIThreadScheduleOnce:
529 PyConfig.GUIThreadScheduleOnce = []
530 _root.InstallGUIEventInputHook()
534 self.__dict__[
'keeppolling' ] = 1
535 self.__dict__[
'PyGUIThread' ] = \
536 threading.Thread(
None, _processRootEvents,
None, ( self, ) )
538 def _finishSchedule( ROOT = self ):
540 if threading.currentThread() != self.PyGUIThread:
541 while self.PyConfig.GUIThreadScheduleOnce:
542 self.PyGUIThread.join( 0.1 )
544 self.PyGUIThread.finishSchedule = _finishSchedule
545 self.PyGUIThread.setDaemon( 1 )
546 self.PyGUIThread.start()
549 for name
in self.module.__pseudo__all__ + _memPolicyAPI + _sigPolicyAPI:
550 self.__dict__[ name ] = getattr( _root, name )
553 setattr( _root,
'NULL', 0 )
555 for name
in cppyy.gbl.std.stlclasses:
556 setattr( _root, name, getattr( cppyy.gbl.std, name ) )
559 sys.displayhook = _displayhook
563 _root.gSystem.Load(
"libMathCore" )
565 sys.modules[ __name__ ] =
ModuleFacade( sys.modules[ __name__ ] )
570 if '__IPYTHON__' in __builtins__
and __IPYTHON__:
571 from IPython
import get_ipython
572 pre_execute_callbacks = get_ipython().events.callbacks[
'pre_execute']
573 zmqIshellName =
'ZMQInteractiveShell'
574 if any(zmqIshellName == callBack.im_class.__name__
for callBack
in pre_execute_callbacks
if hasattr(callBack,
'im_class')):
581 isCocoa = _root.gSystem.InheritsFrom(
'TMacOSXSystem' )
585 sys.displayhook = sys.__displayhook__
586 if not '__IPYTHON__' in __builtins__:
587 sys.excepthook = sys.__excepthook__
588 __builtin__.__import__ = _orig_ihook
590 facade = sys.modules[ __name__ ]
593 _root.RemoveGUIEventInputHook()
596 del facade.__class__.__getattr__
597 del facade.__class__.__setattr__
600 if hasattr( facade,
'PyGUIThread' ):
601 facade.keeppolling = 0
605 if threading.currentThread() != facade.PyGUIThread:
606 facade.PyGUIThread.join( 3. )
611 items = facade.module.__dict__.items()
613 if type(v) == types.ModuleType:
614 facade.module.__dict__[ k ] =
None
615 del v, k, items, types
618 facade.__dict__.clear()
624 gROOT = sys.modules[
'libPyROOT' ].gROOT
625 gROOT.EndOfProcessCleanups()
629 sys.modules[
'libPyROOT' ]._DestroyPyStrings()
632 del sys.modules[
'libPyROOT' ]
633 del sys.modules[
'ROOT' ]
635 atexit.register( cleanup )
allow loading ROOT classes as attributes ---------------------------------—
configuration ------------------------------------------------------------—
def __setattr1(self, name, value)
def __setattr2(self, name, value)
def __getattr__(self, what)
def _importhook(name, args, kwds)
def global_matches(self, text)
def split(str)
helpers ------------------------------------------------------------------—
def _processRootEvents(controller)
helper to prevent GUIs from starving
def __getattr1(self, name)
def __setGTS(self, value)
def file_matches(self, text)
def __getattr2(self, name)
def __delattr__(self, name)
def attr_matches(self, text)
_orig_dhook
call EndOfLineAction after each interactive command (to update display etc.)
def _excepthook(exctype, value, traceb)
RINT command emulation ---------------------------------------------------—.
def __init__(self, module)
put std namespace directly onto ROOT ----------------------------------——
def __init__(self, klass, func)