-
Notifications
You must be signed in to change notification settings - Fork 0
/
cached.py
executable file
·157 lines (101 loc) · 3.75 KB
/
cached.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#! /usr/bin/python
#--------------------------------------------------------------------
# PROGRAM : cached.py
# CREATED BY : hjkim @IIS.2015-12-11 20:18:07.598840
# MODIFED BY :
#
# USAGE : $ ./cached.py
#
# DESCRIPTION:
#------------------------------------------------------cf0.2@20120401
import os,sys,types
from optparse import OptionParser
from cStringIO import StringIO
import lz4
from numpy import load, save, array
class Cached( object ):
'''
mode in ['cached', 'update', 'skip', False]
name : name of cached files i
type is <type 'str'>, function
first arg will be the name of function called followed by args
dir : directory to store cached file
compress: compress option in ['lz4', False]
verbose : print details to screen
'''
mode = 'cached'
verbose = True
def __init__(self, dir, name=None, mode=None, verbose=None, compress='lz4'):
self.dir = dir
self.compress = compress
if name != None:
self.name = name
else:
self.name = lambda fnName, A: '%s_%s'%(fnName, '.'.join( map(str,A) ))
if mode != None:
self.mode = mode
if verbose != None:
self.verbose= verbose
def __call__(self, func):
def wrapper( *args, **kwargs):
if 'CACHED' in kwargs:
Option = kwargs.pop( 'CACHED' )
for k,v in Option.items():
self.__dict__[ k ] = v
for k,v in kwargs.items():
if k.startswith('CACHED_'):
self.__dict__[ k.split('_')[1].lower() ] = v
if self.mode in [False, 'skip']:
return func( *args, **kwargs )
if type(self.name) != str:
name = self.name( func.__name__, args )
else:
name = self.name
if not os.path.exists(self.dir) : os.makedirs(self.dir)
cachePath = os.path.join(self.dir, name)
if self.compress not in [False, None]:
cachePath = cachePath + '.%s'%self.compress
if os.path.exists( cachePath ) and self.mode != 'update':
if self.compress != 'lz4':
cached = open(cachePath,'r')
else:
cached = StringIO( lz4.loads( open(cachePath,'r').read() ) )
if self.verbose: print '\t!! Cached from %s'%cachePath
return load( cached )
else:
aOut = func( *args, **kwargs )
if self.compress=='lz4':
cached = StringIO()
save( cached, aOut )
open(cachePath,'w').write( lz4.dumps( cached.getvalue() ) )
else:
save( open(cachePath,'w'), aOut )
if self.verbose: print '\t!! Cached to %s'%cachePath
return aOut
return wrapper
@Cached( './test' )
def test( n ):
return array( range( n ) )
def test2( n ):
return array( range( n )[::-1] )
def main(args,opts):
import time
nCnt = 10000
print test( nCnt )
print Cached( './test2' )(test2)( nCnt )
print args
print opts
return
if __name__=='__main__':
usage = 'usage: %prog [options] arg'
version = '%prog 1.0'
parser = OptionParser(usage=usage,version=version)
# parser.add_option('-r','--rescan',action='store_true',dest='rescan',
# help='rescan all directory to find missing file')
(options,args) = parser.parse_args()
# if len(args) == 0:
# parser.print_help()
# else:
# main(args,options)
# LOG = LOGGER()
main(args,options)