ATLAS Offline Software
Loading...
Searching...
No Matches
AtlRunQueryCache.py
Go to the documentation of this file.
1#!/bin/env python
2
3# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
4
5import pickle
6import os
7import sys
8
9DEBUG=False
10
12 def __init__(self,cachedir,form):
13 self._cache = {}
14 self.cachedir = cachedir.rstrip('/') if os.path.exists(cachedir) else None
15 self.form = form
16 if self.cachedir:
17 print ("Initializing the cache at",cachedir.rstrip('/'))
18
19
20 def __call__(self, f, *args, **kwds):
21 if not self.cachedir:
22 return f # caching is automatically disabled if no cache directory exists
23
24 print ("Providing cache functionality for function '%s()'" % f.func_name)
25 def newf(*args, **kwds):
26 key = kwds['cachekey']
27 if not self.__is_cached(key):
28 self.__write_to_cache(key,f(*args, **kwds))
29 else:
30 if DEBUG:
31 print ("DEBUG: returning cached value for '%s'" % (self.form % key))
32 pass
33 return self._cache[key]
34 return newf
35
36 def __name_pickle_cache(self,key):
37 filename = self.form % key
38 return '%s/%s.pickle' % (self.cachedir, filename)
39
40
41 def __write_to_cache(self,key, value):
42 # put into transient cache
43 self._cache[key] = value
44
45 # store pickled version
46 pfname = self.__name_pickle_cache(key)
47 pf = open( pfname, 'w' )
48 try:
49 pickle.dump(value, pf)
50 except pickle.PicklingError as err:
51 print ('ERROR: could not write to cache: %s (%s)' % (pfname, err))
52 sys.exit(1)
53 pf.close()
54
55 def __is_cached(self,key):
56 # check transient cache
57 if key in self._cache:
58 return True
59
60 # check for pickled version
61 pfname = self.__name_pickle_cache(key)
62 try:
63 pf = open( pfname, 'r' )
64 except OSError:
65 if DEBUG:
66 print ('DEBUG: could not read from cache: ' + pfname)
67 return False
68 try:
69 self._cache[key] = pickle.load(pf)
70 except pickle.UnpicklingError as err:
71 print ("ERROR: could not unpickle %s (%s)" % (pfname, err))
72 sys.exit(1)
73 pf.close()
74 return True
75
76
77
78
79
80if __name__ == "__main__":
81 @Cache("/afs/cern.ch/user/s/stelzer/runsummary/cache/","simple_%i_second%i")
82 def aFunction(x,y,cachekey):
83 print ("expensive")
84 return (3*x,y*y,x+y)
85
86 x=13
87 print (aFunction(x,y=2,cachekey=(x,2)))
88 print (aFunction(x,1,cachekey=(x,1)))
89