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',
'_gts' ]
137 if not callable( c ):
138 raise ValueError(
'"%s" is not callable' % str(c) );
144 GUIThreadScheduleOnce = property( __getGTS, __setGTS )
151 _root.SetMemoryPolicy( _root.kMemoryHeuristics )
152 _root.SetSignalPolicy( _root.kSignalSafe )
156 __pseudo__all__ = [
'gROOT',
'gSystem',
'gInterpreter',
157 'AddressOf',
'MakeNullPointer',
'Template',
'std' ]
160 _orig_ehook = sys.excepthook
163 _memPolicyAPI = [
'SetMemoryPolicy',
'SetOwnership',
'kMemoryHeuristics',
'kMemoryStrict' ]
164 _sigPolicyAPI = [
'SetSignalPolicy',
'kSignalFast',
'kSignalSafe' ]
169 npos = str.find(
' ' )
171 return str[:npos], str[npos+1:]
177 _root.std = cppyy.gbl.std
178 sys.modules[
'ROOT.std'] = cppyy.gbl.std
184 c = _root.CreateScopeProxy( klass )
188 return getattr( self.__dict__[
'func' ](), what )
191 return cmp( self.
func(), other )
199 return repr( self.
func() )
202 return str( self.
func() )
214 bytes_read = self.GetEntry(i)
215 while 0 < bytes_read:
218 bytes_read = self.GetEntry(i)
221 raise RuntimeError(
"TTree I/O error" )
223 _root.CreateScopeProxy(
"TTree" ).__iter__ = _TTree__iter__
229 if isinstance( value, SyntaxError )
and value.text:
230 cmd, arg =
split( value.text[:-1] )
235 elif cmd ==
'.?' or cmd ==
'.help':
236 sys.stdout.write(
"""PyROOT emulation of Cling commands.
237 All emulated commands must be preceded by a . (dot).
238 ===========================================================================
241 Shell: ![shell] : execute shell command
242 Evaluation: x [file] : load [file] and evaluate {statements} in the file
243 Load/Unload: L [lib] : load [lib]
244 Quit: q : quit python session
246 The standard python help system is available through a call to 'help()' or
247 'help(<id>)' where <id> is an identifier, e.g. a class or function such as
248 TPad or TPad.cd, etc.
251 elif cmd ==
'.!' and arg:
252 return os.system( arg )
253 elif cmd ==
'.x' and arg:
255 fn = os.path.expanduser( os.path.expandvars( arg ) )
256 execfile( fn, __main__.__dict__, __main__.__dict__ )
259 return _root.gSystem.Load( arg )
260 elif cmd ==
'.cd' and arg:
264 return sys.modules[ __name__ ].gDirectory.ls()
266 return sys.modules[ __name__ ].gDirectory.pwd()
267 elif isinstance( value, SyntaxError )
and \
268 value.msg ==
"can't assign to function call":
269 sys.stdout.write(
"""Are you trying to assign a value to a reference return, for example to the
270 result of a call to "double& SMatrix<>::operator()(int,int)"? If so, then
271 please use operator[] instead, as in e.g. "mymatrix[i][j] = somevalue".
277 if not '__IPYTHON__' in __builtins__:
279 sys.excepthook = _excepthook
283 _orig_dhook = sys.displayhook
285 _root.gInterpreter.EndOfLineAction()
293 import builtins
as __builtin__
294 _orig_ihook = __builtin__.__import__
296 if name[0:5] ==
'ROOT.':
298 sys.modules[ name ] = getattr( sys.modules[
'ROOT' ], name[5:] )
303 __builtin__.__import__ = _importhook
309 gSystemProcessEvents = _root.gSystem.ProcessEvents
311 if sys.platform ==
'win32':
313 _root.gROOT.ProcessLineSync(
'((TGWin32 *)gVirtualX)->SetUserThreadId(%ld)' % (thread.get_ident()))
315 while controller.keeppolling:
317 gSystemProcessEvents()
318 if PyConfig.GUIThreadScheduleOnce:
319 for guicall
in PyConfig.GUIThreadScheduleOnce:
321 PyConfig.GUIThreadScheduleOnce = []
330 types.ModuleType.__init__( self,
'ROOT' )
332 self.__dict__[
'module' ] = module
334 self.__dict__[
'__doc__' ] = self.module.__doc__
335 self.__dict__[
'__name__' ] = self.module.__name__
336 self.__dict__[
'__file__' ] = self.module.__file__
338 self.__dict__[
'keeppolling' ] = 0
339 self.__dict__[
'PyConfig' ] = self.module.PyConfig
341 class gROOTWrapper( object ):
342 def __init__( self, gROOT, master ):
343 self.__dict__[
'_master' ] = master
344 self.__dict__[
'_gROOT' ] = gROOT
346 def __getattr__( self, name ):
347 if name !=
'SetBatch' and self._master.__dict__[
'gROOT' ] != self._gROOT:
348 self._master._ModuleFacade__finalSetup()
349 del self._master.__class__._ModuleFacade__finalSetup
350 return getattr( self._gROOT, name )
352 def __setattr__( self, name, value ):
353 return setattr( self._gROOT, name, value )
355 self.__dict__[
'gROOT' ] = gROOTWrapper( _root.gROOT, self )
359 self.__class__.__getattr__ = self.__class__.__getattr1
360 del self.__class__.__getattr1
361 self.__class__.__setattr__ = self.__class__.__setattr1
362 del self.__class__.__setattr1
367 del self.__class__.__finalSetup
370 return setattr( self, name, value )
374 if not name
in self.__dict__:
377 setattr( self.__class__, name, _root.GetCppGlobal( name ) )
380 if sys.hexversion >= 0x3000000:
384 tcnv = { bool :
'bool %s = %d;',
385 int :
'int %s = %d;',
386 pylong :
'long %s = %d;',
387 float :
'double %s = %f;',
388 str :
'string %s = "%s";' }
390 _root.gROOT.ProcessLine( tcnv[
type(value) ] % (name,value) );
391 setattr( self.__class__, name, _root.GetCppGlobal( name ) )
396 return super( self.__class__, self ).__setattr__( name, value )
400 if name ==
'__path__':
401 raise AttributeError( name )
405 del self.__class__.__finalSetup
408 return getattr( self, name )
412 if name ==
'__all__':
413 if '__IPYTHON__' in __builtins__:
415 warnings.warn(
'"from ROOT import *" is not supported under IPython' )
418 caller = sys.modules[ sys._getframe( 1 ).f_globals[
'__name__' ] ]
422 caller = sys.modules[ sys._getframe( 2 ).f_globals[
'__name__' ] ]
425 for name
in self.module.__pseudo__all__:
426 caller.__dict__[ name ] = getattr( _root, name )
429 _root.SetRootLazyLookup( caller.__dict__ )
432 return self.module.__all__
436 attr = _root.LookupCppEntity( name, PyConfig.ExposeCppMacros )
437 if type(attr) == _root.PropertyProxy:
438 setattr( self.__class__, name, attr )
439 return getattr( self, name )
441 self.__dict__[ name ] = attr
443 except AttributeError:
447 raise AttributeError( name )
452 delattr( self.module._root, name )
453 except AttributeError:
456 return super( self.__class__, self ).
__delattr__( name )
460 self.__dict__[
'gROOT' ] = _root.gROOT
463 self.__class__.__getattr__ = self.__class__.__getattr2
464 del self.__class__.__getattr2
465 self.__class__.__setattr__ = self.__class__.__setattr2
466 del self.__class__.__setattr2
470 hasargv = hasattr( sys,
'argv' )
471 if hasargv
and PyConfig.IgnoreCommandLineOptions:
475 appc = _root.CreateScopeProxy(
'PyROOT::TPyROOTApplication' )
476 if appc.CreatePyROOTApplication():
477 appc.InitROOTGlobals()
479 appc.InitROOTMessageCallback();
481 if hasargv
and PyConfig.IgnoreCommandLineOptions:
485 if '__IPYTHON__' in __builtins__:
487 _root.gROOT.ProcessLine(
'TPython::Exec( "" );' )
488 sys.modules[
'__main__' ].__builtins__ = __builtins__
491 if hasattr( cppyy.gbl.std,
'__1' ):
492 attr_1 = getattr( cppyy.gbl.std,
'__1' )
493 if hasattr( attr_1,
'cout' ):
494 self.__dict__[
'cout' ] = attr_1.cout
497 if hasargv
and not '-n' in sys.argv:
498 rootlogon = os.path.expanduser(
'~/.rootlogon.py' )
499 if os.path.exists( rootlogon ):
502 imp.load_module(
'rootlogon',
open( rootlogon,
'r' ), rootlogon, ('.py','
r',1) )
508 name =
'.rootlogon.C'
509 logons = [ os.path.join( str(self.gRootDir),
'etc',
'system' + name ),
510 os.path.expanduser( os.path.join(
'~', name ) ) ]
511 if logons[-1] != os.path.join( os.getcwd(), name ):
512 logons.append( name )
513 for rootlogon
in logons:
514 if os.path.exists( rootlogon ):
515 appc.ExecuteFile( rootlogon )
516 del rootlogon, logons
519 if self.PyConfig.StartGuiThread
and \
520 not ( self.keeppolling
or _root.gROOT.IsBatch() ):
521 if self.PyConfig.StartGuiThread ==
'inputhook' or\
522 _root.gSystem.InheritsFrom(
'TMacOSXSystem' ):
524 if PyConfig.GUIThreadScheduleOnce:
525 for guicall
in PyConfig.GUIThreadScheduleOnce:
527 PyConfig.GUIThreadScheduleOnce = []
528 _root.InstallGUIEventInputHook()
532 self.__dict__[
'keeppolling' ] = 1
533 self.__dict__[
'PyGUIThread' ] = \
534 threading.Thread(
None, _processRootEvents,
None, ( self, ) )
536 def _finishSchedule( ROOT = self ):
538 if threading.currentThread() != self.PyGUIThread:
539 while self.PyConfig.GUIThreadScheduleOnce:
540 self.PyGUIThread.join( 0.1 )
542 self.PyGUIThread.finishSchedule = _finishSchedule
543 self.PyGUIThread.setDaemon( 1 )
544 self.PyGUIThread.start()
547 for name
in self.module.__pseudo__all__ + _memPolicyAPI + _sigPolicyAPI:
548 self.__dict__[ name ] = getattr( _root, name )
551 setattr( _root,
'NULL', 0 )
553 for name
in cppyy.gbl.std.stlclasses:
554 setattr( _root, name, getattr( cppyy.gbl.std, name ) )
557 sys.displayhook = _displayhook
561 _root.gSystem.Load(
"libMathCore" )
563 sys.modules[ __name__ ] =
ModuleFacade( sys.modules[ __name__ ] )
568 if '__IPYTHON__' in __builtins__
and __IPYTHON__:
569 from IPython
import get_ipython
570 pre_execute_callbacks = get_ipython().events.callbacks[
'pre_execute']
571 zmqIshellName =
'ZMQInteractiveShell'
572 if any(zmqIshellName == callBack.im_class.__name__
for callBack
in pre_execute_callbacks
if hasattr(callBack,
'im_class')):
579 isCocoa = _root.gSystem.InheritsFrom(
'TMacOSXSystem' )
583 sys.displayhook = sys.__displayhook__
584 if not '__IPYTHON__' in __builtins__:
585 sys.excepthook = sys.__excepthook__
586 __builtin__.__import__ = _orig_ihook
588 facade = sys.modules[ __name__ ]
591 _root.RemoveGUIEventInputHook()
594 del facade.__class__.__getattr__
595 del facade.__class__.__setattr__
598 if hasattr( facade,
'PyGUIThread' ):
599 facade.keeppolling = 0
603 if threading.currentThread() != facade.PyGUIThread:
604 facade.PyGUIThread.join( 3. )
609 items = facade.module.__dict__.items()
611 if type(v) == types.ModuleType:
612 facade.module.__dict__[ k ] =
None
613 del v, k, items, types
616 facade.__dict__.clear()
622 gROOT = sys.modules[
'libPyROOT' ].gROOT
623 gROOT.EndOfProcessCleanups()
627 sys.modules[
'libPyROOT' ]._DestroyPyStrings()
630 del sys.modules[
'libPyROOT' ]
631 del sys.modules[
'ROOT' ]
633 atexit.register( cleanup )
allow loading ROOT classes as attributes ---------------------------------—
def _processRootEvents
helper to prevent GUIs from starving
def split
helpers ------------------------------------------------------------------—
configuration ------------------------------------------------------------—
def _excepthook
RINT command emulation ---------------------------------------------------—.
_orig_dhook
call EndOfLineAction after each interactive command (to update display etc.)
put std namespace directly onto ROOT ----------------------------------——