source: sasview/DataLoader/loader.py @ aa749ac

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 aa749ac was aa749ac, checked in by Gervaise Alina <gervyh@…>, 16 years ago
  • Property mode set to 100644
File size: 3.4 KB
Line 
1# This program is public domain
2"""
3File extension registry.
4
5This provides routines for opening files based on extension,
6and registers the built-in file extensions.
7"""
8import logging
9import os.path
10
11class Loader(object):
12    """
13    Associate a file loader with an extension.
14
15    Note that there may be multiple readers for the same extension.
16
17    Example:
18
19    registry = Loader()
20
21    # Add an association by setting an element
22    registry['.zip'] = unzip
23
24    # Multiple extensions for one loader
25    registry['.tgz'] = untar
26    registry['.tar.gz'] = untar
27
28    # Multiple readers for one extension
29    registry['.cx'] = cx1
30    registry['.cx'] = cx2
31    registry['.cx'] = cx3
32   
33    # Can also register a format name for explicit control from caller
34    registry['cx3'] = cx3
35
36    # Retrieve readers for a file name
37    registry.lookup('hello.cx') -> [cx3,cx2,cx1]
38
39    # Run loader on a filename
40    registry.load('hello.cx') ->
41        try:
42            return cx3('hello.cx')
43        except:
44            try:
45                return cx2('hello.cx')
46            except:
47                return cx1('hello.cx')
48
49    # Load in a specific format ignoring extension
50    registry.load('hello.cx',format='cx3') ->
51        return cx3('hello.cx')
52    """
53    def __init__(self):
54        self.readers = {}
55        self.reading=None
56       
57       
58    def __setitem__(self, ext, reader):
59        if ext not in self.readers:
60            self.readers[ext] = []
61        self.readers[ext].insert(0,reader)
62       
63       
64    def __getitem__(self, ext):
65        return self.readers[ext]
66   
67   
68    def __contains__(self, ext):
69        return ext in self.readers
70   
71   
72    def formats(self, name=True, ext=False):
73        """
74        Return a list of the registered formats.  If name=True then
75        named formats are returned.  If ext=True then extensions
76        are returned.
77        """
78        names = [a for a in self.readers.keys() if not a.startswith('.')]
79        exts = [a for a in self.readers.keys() if a.startswith('.')]
80        names.sort()
81        exts.sort()
82        ret = []
83        if name: ret += names
84        if ext: ret += exts
85        return ret
86       
87    def lookup(self, path):
88        """
89        Return the loader associated with the file type of path.
90        """       
91        file = os.path.basename(path)
92        idx = file.find('.')
93        ext = file[idx:] if idx >= 0 else ''
94        try:
95            return self.readers[ext]
96        except:
97            #raise ValueError, "Unknown file type '%s'"%ext
98            print  "Unknown file type '%s'"%ext
99 
100               
101    def getAcTReader(self,path):
102        return self.reading
103   
104    def load(self, path, format=None):
105        """
106        Call the loader for the file type of path.
107
108        Raises ValueError if no loader is available.
109        May raise a loader-defined exception if loader fails.
110        """
111        if format is None:
112            readers = self.lookup(path)
113        else:
114            readers = self.readers[format]
115        if readers!=None:
116            for fn in readers:
117                try:
118                    value=fn.read(path)
119                    self.reading= fn.__class__
120                    return value
121                except ValueError,msg:
122                    print str(msg)
Note: See TracBrowser for help on using the repository browser.