1 | # This program is public domain |
---|
2 | """ |
---|
3 | File extension registry. |
---|
4 | |
---|
5 | This provides routines for opening files based on extension, |
---|
6 | and registers the built-in file extensions. |
---|
7 | """ |
---|
8 | import imp,os,sys |
---|
9 | import logging |
---|
10 | import os.path |
---|
11 | |
---|
12 | |
---|
13 | def _findReaders(dir): |
---|
14 | # List of plugin objects |
---|
15 | plugins = [] |
---|
16 | # Go through files in plug-in directory |
---|
17 | try: |
---|
18 | |
---|
19 | list = os.listdir(dir) |
---|
20 | for item in list: |
---|
21 | |
---|
22 | toks = os.path.splitext(os.path.basename(item)) |
---|
23 | if toks[1]=='.py' and not toks[0]=='__init__': |
---|
24 | name = toks[0] |
---|
25 | path = [os.path.abspath(dir)] |
---|
26 | file = None |
---|
27 | |
---|
28 | try: |
---|
29 | (file, path, info) = imp.find_module(name, path) |
---|
30 | module = imp.load_module( name, file, item, info ) |
---|
31 | if hasattr(module, "Reader"): |
---|
32 | try: |
---|
33 | plugins.append(module.Reader()) |
---|
34 | except: |
---|
35 | log("Error accessing Reader in %s\n %s" % (name, sys.exc_value)) |
---|
36 | except : |
---|
37 | log("Error importing %s\n %s" % (name, sys.exc_value)) |
---|
38 | finally: |
---|
39 | if not file==None: |
---|
40 | file.close() |
---|
41 | except: |
---|
42 | # Should raise and catch at a higher level and display error on status bar |
---|
43 | pass |
---|
44 | return plugins |
---|
45 | class Loader(object): |
---|
46 | """ |
---|
47 | Associate a file loader with an extension. |
---|
48 | |
---|
49 | Note that there may be multiple readers for the same extension. |
---|
50 | |
---|
51 | Example: |
---|
52 | |
---|
53 | registry = Loader() |
---|
54 | |
---|
55 | # Add an association by setting an element |
---|
56 | registry['.zip'] = unzip |
---|
57 | |
---|
58 | # Multiple extensions for one loader |
---|
59 | registry['.tgz'] = untar |
---|
60 | registry['.tar.gz'] = untar |
---|
61 | |
---|
62 | # Multiple readers for one extension |
---|
63 | registry['.cx'] = cx1 |
---|
64 | registry['.cx'] = cx2 |
---|
65 | registry['.cx'] = cx3 |
---|
66 | |
---|
67 | # Can also register a format name for explicit control from caller |
---|
68 | registry['cx3'] = cx3 |
---|
69 | |
---|
70 | # Retrieve readers for a file name |
---|
71 | registry.lookup('hello.cx') -> [cx3,cx2,cx1] |
---|
72 | |
---|
73 | # Run loader on a filename |
---|
74 | registry.load('hello.cx') -> |
---|
75 | try: |
---|
76 | return cx3('hello.cx') |
---|
77 | except: |
---|
78 | try: |
---|
79 | return cx2('hello.cx') |
---|
80 | except: |
---|
81 | return cx1('hello.cx') |
---|
82 | |
---|
83 | # Load in a specific format ignoring extension |
---|
84 | registry.load('hello.cx',format='cx3') -> |
---|
85 | return cx3('hello.cx') |
---|
86 | """ |
---|
87 | def __init__(self): |
---|
88 | self.readers = {} |
---|
89 | self.reading=None |
---|
90 | self.dir='plugins' |
---|
91 | self.__setitem__() |
---|
92 | |
---|
93 | def set_pluginDir (self,path): |
---|
94 | """ specify the name of folder containing pluging""" |
---|
95 | if not os.path.isdir(path): |
---|
96 | os.mkdir(path) |
---|
97 | self.dir=path |
---|
98 | def __setitem__(self, ext=None, reader=None): |
---|
99 | if reader==None: |
---|
100 | plugReader=None |
---|
101 | if os.path.isdir(self.dir): |
---|
102 | plugReader=_findReaders(self.dir)# import all module in plugins |
---|
103 | elif os.path.isdir('../'+self.dir): |
---|
104 | plugReader=_findReaders('../'+self.dir) |
---|
105 | if plugReader !=None: |
---|
106 | for preader in plugReader:# for each modules takes list of extensions |
---|
107 | #print preader.ext |
---|
108 | for item in preader.ext: |
---|
109 | ext=item |
---|
110 | if ext not in self.readers:#assign extension with its reader |
---|
111 | self.readers[ext] = [] |
---|
112 | self.readers[ext].insert(0,preader) |
---|
113 | else: |
---|
114 | if ext not in self.readers: |
---|
115 | self.readers[ext] = [] |
---|
116 | self.readers[ext].insert(0,reader) |
---|
117 | |
---|
118 | |
---|
119 | def __getitem__(self, ext): |
---|
120 | return self.readers[ext] |
---|
121 | |
---|
122 | |
---|
123 | |
---|
124 | def __contains__(self, ext): |
---|
125 | return ext in self.readers |
---|
126 | |
---|
127 | |
---|
128 | def formats(self, name=True, ext=False): |
---|
129 | """ |
---|
130 | Return a list of the registered formats. If name=True then |
---|
131 | named formats are returned. If ext=True then extensions |
---|
132 | are returned. |
---|
133 | """ |
---|
134 | names = [a for a in self.readers.keys() if not a.startswith('.')] |
---|
135 | exts = [a for a in self.readers.keys() if a.startswith('.')] |
---|
136 | names.sort() |
---|
137 | exts.sort() |
---|
138 | ret = [] |
---|
139 | if name: ret += names |
---|
140 | if ext: ret += exts |
---|
141 | return ret |
---|
142 | |
---|
143 | def lookup(self, path): |
---|
144 | """ |
---|
145 | Return the reader associated with the file type of path. |
---|
146 | """ |
---|
147 | file = os.path.basename(path) |
---|
148 | idx = file.find('.') |
---|
149 | ext = file[idx:] if idx >= 0 else '' |
---|
150 | try: |
---|
151 | return self.readers[ext] |
---|
152 | except: |
---|
153 | #raise ValueError, "Unknown file type '%s'"%ext |
---|
154 | print "Unknown file type '%s'"%ext |
---|
155 | |
---|
156 | |
---|
157 | def getAcTReader(self,path): |
---|
158 | """ return Reader actually reading""" |
---|
159 | return self.reading |
---|
160 | |
---|
161 | def load(self, path, format=None): |
---|
162 | """ |
---|
163 | Call the loader for the file type of path. |
---|
164 | |
---|
165 | Raises ValueError if no loader is available. |
---|
166 | May raise a loader-defined exception if loader fails. |
---|
167 | """ |
---|
168 | if format is None: |
---|
169 | readers = self.lookup(path) |
---|
170 | else: |
---|
171 | readers = self.readers[format] |
---|
172 | if readers!=None: |
---|
173 | for fn in readers: |
---|
174 | try: |
---|
175 | value=fn.read(path) |
---|
176 | self.reading= fn.__class__ |
---|
177 | return value |
---|
178 | except ValueError,msg: |
---|
179 | print str(msg) |
---|
180 | if __name__=="__main__": |
---|
181 | l=Loader() |
---|
182 | print "look up",l.lookup('angles_flat.png') |
---|
183 | print l.__getitem__('.tiff') |
---|
184 | print l.__getitem__('jpeg') |
---|
185 | print l.__contains__('.tiff') |
---|
186 | |
---|