source: sasview/DataLoader/loader.py @ d6513cd

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2release_4.0.1ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since d6513cd was 77c1c29d, checked in by Gervaise Alina <gervyh@…>, 16 years ago

comment added

  • Property mode set to 100644
File size: 9.5 KB
RevLine 
[a916ccc]1# This program is public domain
2"""
[d22da51]3    @organization: Module loader contains class Loader which uses
4    some readers to return values contained in a file readed.
[77c1c29d]5    @ author : Paul Kienzler
6    @modifiied by gervaise alina
[a916ccc]7"""
8import imp,os,sys
9import logging
10import os.path
[d22da51]11logging.basicConfig(level=logging.ERROR,
12                    format='%(asctime)s %(levelname)s %(message)s',
[d3619421]13                    filename='test_log.txt',
[d22da51]14                    filemode='w')
15
[a916ccc]16def _findReaders(dir):
17    # List of plugin objects
18    plugins = []
19    # Go through files in plug-in directory
20    try:
21       
22        list = os.listdir(dir)
23        for item in list:
24           
25            toks = os.path.splitext(os.path.basename(item))
26            if toks[1]=='.py' and not toks[0]=='__init__':
27                name = toks[0]
28                path = [os.path.abspath(dir)]
29                file = None
30                try:
31                    (file, path, info) = imp.find_module(name, path)
32                    module = imp.load_module( name, file, item, info )
33                    if hasattr(module, "Reader"):
34                        try:
35                            plugins.append(module.Reader())
36                        except:
[94daf8a]37                            logging.error("Error accessing Reader in %s\n  %s" % (name, sys.exc_value))
[a916ccc]38                except :
[94daf8a]39                    logging.error("Error importing %s\n  %s" % (name, sys.exc_value))
[a916ccc]40                finally:
41                    if not file==None:
42                        file.close()
43    except:
44        # Should raise and catch at a higher level and display error on status bar
45        pass   
46    return plugins
[d22da51]47
48
[1b0b3ca]49class Loader(object):
[d22da51]50    """
51        Loader class extracts data from a given file.
52        This provides routines for opening files based on extension,
53        and readers built-in file extensions.
54        It uses functionalities for class Load
55        @note: For loader to operate properly each readers used should
56        contain a class name "Reader" that contains a field call ext.
57        Can be used as follow:
58        L=Loader()
59        self.assertEqual(l.__contains__('.tiff'),True)
60        #Recieves data
61        data=L.load(path)
62    """
63    #Store instance of class Load
[a916ccc]64    __load = None
[d22da51]65   
66   
[1b0b3ca]67    class Load(object):
[a916ccc]68   
69        def __init__(self):
[d22da51]70            #Dictionary containing readers and extension as keys
[a916ccc]71            self.readers = {}
[d22da51]72            #Load all readers in plugins
[1b0b3ca]73            self.__setitem__()
[d22da51]74           
[a916ccc]75           
[2fd516b]76        def __setitem__(self,dir=None, ext=None, reader=None):
[d22da51]77            """
78                __setitem__  sets in a dictionary(self.readers) a given reader
79                with a file extension that it can read.
80                @param ext: extension given of type string
81                @param reader:instance Reader class
[2fd516b]82                @param dir: directory name where plugins readers will be saved
[d22da51]83                @raise : ValueError will be raise if a "plugins" directory is not found
84                and the user didn't add a reader as parameter or if the user didn't
85                add a reader as a parameter and plugins directory doesn't contain
86                plugin reader.
87                if an extension is not specified and a reader does not contain a field
[d3619421]88                ext , a warning is printed in test_log.txt file.
[d22da51]89                @note: when called without parameters __setitem__ will try to load
[2fd516b]90                readers inside a "readers" directory
91                if call with a directory name will try find readers
92                from that directory "dir"
[d22da51]93            """
[2fd516b]94            if dir==None:
[d3619421]95                dir = 'readers'
96            dir=os.path.join(os.path.dirname(os.path.abspath(__file__)),dir)
[16d8e5f]97           
[8d6440f]98            if (reader==None and  ext==None) or dir:#1st load
[a916ccc]99                plugReader=None
[2fd516b]100                if os.path.isdir(dir):
101                    plugReader=_findReaders(dir)# import all module in plugins
102                if os.path.isdir('../'+dir):
103                    plugReader=_findReaders('../'+dir)
[d3619421]104 
105               
[a916ccc]106                if plugReader !=None:
[d3619421]107                    list=[]
[a916ccc]108                    for preader in plugReader:# for each modules takes list of extensions
[2fd516b]109                        try:
110                            list=preader.ext
[d3619421]111                        except AttributeError,msg:
112                            logging.warning(msg)
113                            pass
114                            #raise  AttributeError," %s instance has no attribute 'ext'"\
115                            #%(preader.__class__)
116                        if list !=[]:
117                            for item in list:
118                                ext=item
119                                if ext not in self.readers:#assign extension with its reader
120                                    self.readers[ext] = []
121                                self.readers[ext].insert(0,preader)
[d22da51]122            #Reader and extension are given
[a916ccc]123            elif reader !=None and  ext !=None:
124                if ext not in self.readers:
125                    self.readers[ext] = []
126                self.readers[ext].insert(0,reader)
127            elif reader!=None:
[d22da51]128                #only reader is receive try to find a field ext
[2fd516b]129                try:
130                    list=preader.ext
131                except:
132                    raise AttributeError," Reader instance has no attribute 'ext'"
133                for item in list:
134               
135                    ext=item
136                    if ext not in self.readers:#assign extension with its reader
137                        self.readers[ext] = []
138                    self.readers[ext].insert(0,reader)
139
[a916ccc]140            else:
141                raise ValueError,"missing reader"
[d22da51]142               
[a916ccc]143           
144        def __getitem__(self, ext):
[d22da51]145            """
146                __getitem__ get a list of readers that can read a file with that extension
147                @param ext: file extension
148                @return self.readers[ext]:list of readers that can read a file
149                with that extension
150            """
[a916ccc]151            return self.readers[ext]
152           
153        def __contains__(self, ext):
[d22da51]154            """
155                @param ext:file extension
156                @return: True or False whether there is a reader file with that extension
157            """
[a916ccc]158            return ext in self.readers
159       
160       
161        def formats(self, name=True, ext=False):
162            """
163            Return a list of the registered formats.  If name=True then
164            named formats are returned.  If ext=True then extensions
165            are returned.
166            """
167            names = [a for a in self.readers.keys() if not a.startswith('.')]
168            exts = [a for a in self.readers.keys() if a.startswith('.')]
169            names.sort()
170            exts.sort()
171            ret = []
172            if name: ret += names
173            if ext: ret += exts
174            return ret
175           
176        def lookup(self, path):
177            """
178            Return the loader associated with the file type of path.
179            """       
180            file = os.path.basename(path)
181            idx = file.find('.')
182            ext = file[idx:] if idx >= 0 else ''
[d22da51]183           
[a916ccc]184            try:
185                return self.readers[ext]
186            except:
[d3619421]187                logging.warning("Unknown file type '%s'"%ext)
[3dd7cce]188                raise RuntimeError, "Unknown file type '%s'"%ext
[d22da51]189               
190       
[a916ccc]191       
192        def load(self, path, format=None):
193            """
[d22da51]194                Call reader for the file type of path.
195                @param path: path to file to load
196                @param format: extension of file to load
197                @return Data if sucessful
198                  or None is not reader was able to read that file
199                Raises ValueError if no reader is available.
200                May raise a loader-defined exception if loader fails.
[a916ccc]201            """
[1b0b3ca]202            try:
203                os.path.isfile( os.path.abspath(path)) 
204            except:
[16d8e5f]205                raise ValueError," file path unknown"
[d22da51]206           
[a916ccc]207            if format is None:
[d22da51]208                try:
209                    readers = self.lookup(path)
[4245594]210                except :
211                    raise 
[a916ccc]212            else:
213                readers = self.readers[format]
214            if readers!=None:
215                for fn in readers:
216                    try:
217                        value=fn.read(path)
218                        return value
[8176aad]219                    except:
220                        logging.error("Load Error: %s"% (sys.exc_value))
[d22da51]221            else:
222                raise ValueError,"Loader contains no reader"
223                       
224                         
[a916ccc]225    def __init__(self):
226        """ Create singleton instance """
227        # Check whether we already have an instance
[1b0b3ca]228        if Loader.__load is None:
[a916ccc]229            # Create and remember instance
[1b0b3ca]230            Loader.__load = Loader.Load()
231            Loader.__load.__setitem__()
[a916ccc]232        # Store instance reference as the only member in the handle
[1b0b3ca]233        self.__dict__['_Loader__load'] = Loader.__load
[a916ccc]234
235    def __getattr__(self, attr):
236        """ Delegate access to implementation """
237        return getattr(self.__load, attr)
238
239    def __setattr__(self, attr, value):
240        """ Delegate access to implementation """
241        return setattr(self.__load, attr, value)
Note: See TracBrowser for help on using the repository browser.