ATLAS Offline Software
Loading...
Searching...
No Matches
PyAthena.py
Go to the documentation of this file.
1# Copyright (C) 2002-2024 CERN for the benefit of the ATLAS collaboration
2
3# @file: PyAthena.py
4# @purpose: a set of Python classes for PyAthena
5# @author: Sebastien Binet <binet@cern.ch>
6
7__doc__ = """Module containing a set of Python base classes for PyAthena"""
8__author__ = "Sebastien Binet <binet@cern.ch>"
9
10
11__all__ = []
12__pseudo_all__ = [ 'StatusCode',
13 'Alg',
14 'Svc',
15 'AlgTool',
16 'Aud',
17 'services',
18 'algs'
19 ]
20
21
23 """ return the OS-native name from an OS-indenpendent one """
24 import sys
25 plat = sys.platform
26 if plat.count('linux')>0:
27 lib_prefix,lib_suffix = 'lib', '.so'
28 elif plat == 'win32':
29 lib_prefix,lib_suffix = '', '.dll'
30 elif plat == 'darwin':
31 lib_prefix,lib_suffix = 'lib','.dylib'
32 else:
33 raise RuntimeError ("sorry platform [%s] is not (yet?) supported"%plat)
34 _sys_libname = libname
35 if not _sys_libname.startswith (lib_prefix):
36 _sys_libname = ''.join([lib_prefix,_sys_libname])
37 if not _sys_libname.endswith (lib_suffix):
38 _sys_libname = ''.join([_sys_libname, lib_suffix])
39 return _sys_libname
40
41def load_library (libname):
42 """
43 Helper method to load a library by its natural name, not the OS-native name.
44 But if the OS-native name is given, it is safely handled too. Note that there's
45 a problem on MacOSX, for which the OS-native name ends with .dylib, but for
46 which ATLAS builds .so libraries. Override the OS-native name (which should probably
47 be replaced by two attempts; one with the .dylib and the other with .so)
48 usage:
49 >>> load_library ('AthenaServices')
50 >>> load_library ('AthenaServicesDict')
51 """
52 _sys_libname = _get_native_libname(libname)
53 from sys import platform
54 if platform == 'darwin':
55 _sys_libname = _sys_libname.replace('.dylib', '.so')
56 import ctypes
57 return ctypes.cdll.LoadLibrary (_sys_libname)
58
59def find_library(libname):
60 """
61 Helper function to find the (full)path to a library given its natural name.
62 @return None on failure
63
64 usage:
65 >>> find_library('AthenaServices')
66 '/afs/cern.ch/.../AtlasCore/[release]/InstallArea/.../libAthenaServices.so
67 """
68 import os
69
75 _sys_libname = _get_native_libname(libname)
76 # FIXME: REALLY not portable...
77 if os.name != 'posix':
78 raise RuntimeError('sorry OS [%s] is not supported' % os.name)
79
80 if 'LD_LIBRARY_PATH' in os.environ:
81 for d in os.environ['LD_LIBRARY_PATH'].split(os.pathsep):
82 lib = os.path.join(d, _sys_libname)
83 if os.path.exists(lib):
84 return lib
85 return
86
87def reload_module (modname):
88 """
89 Helper method to reload a python module by name.
90 This is useful in the usual following case:
91 >>> from Foo import MyAlg
92 >>> assert (not 'Foo' in dir())
93 >>> reload(Foo) # won't work
94 >>> PyAthena.reload_module ('Foo') # will work
95 >>> PyAthena.reload_module (Foo) # will work too
96 """
97 import sys, types
98 from importlib import reload
99 if isinstance (modname, types.ModuleType):
100 modname = modname.__name__
101 if modname in sys.modules:
102 return reload (sys.modules[modname])
103 raise ValueError('no module [%s] could be found'%modname)
104
105def py_reload (*args):
106 """simple minded function to reload objects, methods and modules
107
108 example of usage:
109 >>> # edit and modify the execute methods of some PyAthena.Alg
110 ... # class, then load back that definition
111 >>> PyAthena.py_reload (alg1.execute, alg2.execute)
112 >>> PyAthena.py_reload (alg1.execute)
113 >>> alg1.execute() # will use the new definition
114 >>> theApp.nextEvent() # will also use the new definitions
115 ... # of both alg1 and alg2
116 """
117 import types, sys
118 from importlib import reload
119 for i,arg in enumerate(args):
120 if isinstance (arg, types.ModuleType):
121
122 reload (arg)
123 elif isinstance (arg, types.StringType):
124 # no-op
125 continue
126 elif isinstance (arg, types.MethodType):
127
129 modname = arg.im_self.__class__.__module__
130 module = reload (sys.modules[modname])
131 obj = arg.im_self
132 klass = getattr (module, obj.__class__.__name__)
133 # update the object with the new fct definition
134 fct_name = arg.im_func.__name__
135 new_fct = getattr (klass, fct_name)
136 #new_fct.im_class = klass
137
138 setattr (obj, fct_name,
139 new_fct.__get__(obj))
140 elif hasattr (arg, '__class__'):
141
143 modname = arg.__class__.__module__
144 module = reload (sys.modules[modname])
145 # get the class, in case new methods appeared...
146 klass = getattr (module, arg.__class__.__name__)
147 from AthenaCommon.Configurable import Configurable
148 cfg_methods = dir(Configurable)
149 d = (k for k in dir(klass)
150 if not k.startswith('__') and k not in cfg_methods)
151 for k in d:
152 if not hasattr (arg, k):
153 v = getattr (klass, k)
154 try:
155 v = v.__get__ (arg)
156 except AttributeError:
157 # 'handle' not-yet-set gaudi properties
158 continue
159 setattr (arg, k, v.__get__(arg))
160 # FIXME: should we remove methods which disappeared ?
161 v = getattr (arg, k)
162
165 py_reload (v)
166 else:
167 print ("*** unhandled type: [%s] (arg #%i) ***" % (type(arg),i))
168 pass
169 return
170
171
172from AthenaPython import PyAthenaComps
173from AthenaPython.Bindings import _PyAthenaBindingsCatalog as _pycat
174
175
176import types
177class ModuleFacade(types.ModuleType):
178 """a helper class to allow easy retrieval of automatically generated
179 configurables (stolen from PyRoot)
180 """
181 def __init__( self, module ):
182 types.ModuleType.__init__(self, module.__name__)
183 self.__dict__[ 'module' ] = module
184 self.__dict__[ '__doc__' ] = module.__doc__
185 self.__dict__[ '__name__' ] = module.__name__
186 self.__dict__[ '__file__' ] = module.__file__
187
188 from .Bindings import py_svc
189 self.__dict__ ['py_svc'] = py_svc
190
191 from .Bindings import py_tool
192 self.__dict__ ['py_tool'] = py_tool
193
194 from .Bindings import py_alg
195 self.__dict__ ['py_alg'] = py_alg
196
197 self.__dict__ ['load_library'] = load_library
198 self.__dict__ ['find_library'] = find_library
199 self.__dict__ ['reload_module'] = reload_module
200 self.__dict__ ['py_reload'] = py_reload
201
202 def __getattr__(self, k):
203 if k in self.__dict__:
204 return self.__dict__.get(k)
205 if k.startswith('__'):
206 return types.ModuleType.__getattribute__(self, k)
207 if k in __pseudo_all__: v = getattr(PyAthenaComps, k)
208 else: v = _pycat.init(k)
209 object.__getattribute__(self, '__dict__')[k] = v
210 return v
211
212import sys
213sys.modules[ __name__ ] = ModuleFacade( sys.modules[ __name__ ] )
214del ModuleFacade
T * get(TKey *tobj)
get a TObject* from a TKey* (why can't a TObject be a TKey?)
Definition hcg.cxx:132
std::vector< std::string > split(const std::string &s, const std::string &t=":")
Definition hcg.cxx:179
load_library(libname)
Definition PyAthena.py:41
reload_module(modname)
Definition PyAthena.py:87
py_reload(*args)
Definition PyAthena.py:105
_get_native_libname(libname)
helpers
Definition PyAthena.py:22