source: sasview/DataLoader/register.py @ cbe6dbe

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 cbe6dbe was bb03739, checked in by Gervaise Alina <gervyh@…>, 16 years ago

unit test added.still working on it

  • Property mode set to 100644
File size: 4.0 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 ExtensionRegistry(object):
12    """
13    Associate a file loader with an extension.
14
15    Note that there may be multiple loaders for the same extension.
16
17    Example:
18
19    registry = ExtensionRegistry()
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 loaders 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 loaders 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.loaders = {}
55        self.reader=None
56    def __setitem__(self, ext, loader):
57        if ext not in self.loaders:
58            self.loaders[ext] = []
59        self.loaders[ext].insert(0,loader)
60    def __getitem__(self, ext):
61        return self.loaders[ext]
62    def __contains__(self, ext):
63        return ext in self.loaders
64    def formats(self, name=True, ext=False):
65        """
66        Return a list of the registered formats.  If name=True then
67        named formats are returned.  If ext=True then extensions
68        are returned.
69        """
70        names = [a for a in self.loaders.keys() if not a.startswith('.')]
71        exts = [a for a in self.loaders.keys() if a.startswith('.')]
72        names.sort()
73        exts.sort()
74        ret = []
75        if name: ret += names
76        if ext: ret += exts
77        return ret
78       
79    def lookup(self, path):
80        """
81        Return the loader associated with the file type of path.
82        """       
83        file = os.path.basename(path)
84        idx = file.find('.')
85        ext = file[idx:] if idx >= 0 else ''
86        try:
87            return self.loaders[ext]
88        except:
89            #raise ValueError, "Unknown file type '%s'"%ext
90            print  "Unknown file type '%s'"%ext
91       
92    def loads(self, path, format=None):
93        """
94        Call the loader for the file type of path.
95
96        Raises ValueError if no loader is available.
97        May raise a loader-defined exception if loader fails.
98        """
99        if format is None:
100            loaders = self.lookup(path)
101        else:
102            loaders = self.loaders[format]
103        for fn in loaders:
104            print fn
105            try:
106                value=fn.read(path)
107                self.reader= fn
108                return value
109            except ValueError,msg:
110                #pass
111                print str(msg)
112    def getAcTReader(self,path):
113        return self.reader
114    def load(self, path, format=None):
115        """
116        Call the loader for the file type of path.
117
118        Raises ValueError if no loader is available.
119        May raise a loader-defined exception if loader fails.
120        """
121        if format is None:
122            loaders = self.lookup(path)
123        else:
124            loaders = self.loaders[format]
125        if loaders!=None:
126            for fn in loaders:
127                try:
128                    value=fn.read(path)
129                    self.reader= fn.__class__
130                    return value
131                    #value=fn.read(path)
132                    #return value
133                except ValueError,msg:
134                    #pass
135                    print str(msg)
Note: See TracBrowser for help on using the repository browser.