Changes in / [97c60f8:278ddee] in sasview
- Location:
- src/sas
- Files:
-
- 1 added
- 5 edited
Legend:
- Unmodified
- Added
- Removed
-
src/sas/sascalc/data_util/registry.py
rb699768 r7f75a3f 7 7 """ 8 8 9 import os.path 9 from sas.sascalc.dataloader.loader_exceptions import NoKnownLoaderException 10 10 11 11 12 class ExtensionRegistry(object): … … 61 62 def __init__(self, **kw): 62 63 self.loaders = {} 64 63 65 def __setitem__(self, ext, loader): 64 66 if ext not in self.loaders: 65 67 self.loaders[ext] = [] 66 68 self.loaders[ext].insert(0,loader) 69 67 70 def __getitem__(self, ext): 68 71 return self.loaders[ext] 72 69 73 def __contains__(self, ext): 70 74 return ext in self.loaders 75 71 76 def formats(self): 72 77 """ … … 76 81 names.sort() 77 82 return names 83 78 84 def extensions(self): 79 85 """ … … 83 89 exts.sort() 84 90 return exts 91 85 92 def lookup(self, path): 86 93 """ 87 94 Return the loader associated with the file type of path. 88 95 89 Raises ValueError if file type is not known. 96 :param path: Data file path 97 :raises ValueError: When no loaders are found for the file. 98 :return: List of available readers for the file extension 90 99 """ 91 100 # Find matching extensions … … 105 114 # Raise an error if there are no matching extensions 106 115 if len(loaders) == 0: 107 raise ValueError, "Unknown file type for "+path 108 # All done 116 raise ValueError("Unknown file type for "+path) 109 117 return loaders 118 110 119 def load(self, path, format=None): 111 120 """ 112 121 Call the loader for the file type of path. 113 122 114 Raises ValueErrorif no loader is available.115 Raises KeyErrorif format is not available.116 May raise a loader-defined exception if loader fails. 123 :raise ValueError: if no loader is available. 124 :raise KeyError: if format is not available. 125 May raise a loader-defined exception if loader fails. 117 126 """ 127 loaders = [] 118 128 if format is None: 119 loaders = self.lookup(path) 129 try: 130 loaders = self.lookup(path) 131 except ValueError as e: 132 pass 120 133 else: 121 loaders = self.loaders[format] 134 try: 135 loaders = self.loaders[format] 136 except KeyError as e: 137 pass 122 138 for fn in loaders: 123 139 try: 124 140 return fn(path) 125 except :126 pass # give other loaders a chance to succeed141 except Exception as e: 142 pass # give other loaders a chance to succeed 127 143 # If we get here it is because all loaders failed 128 raise # reraises last exception 129 130 def test(): 131 reg = ExtensionRegistry() 132 class CxError(Exception): pass 133 def cx(file): return 'cx' 134 def new_cx(file): return 'new_cx' 135 def fail_cx(file): raise CxError 136 def cat(file): return 'cat' 137 def gunzip(file): return 'gunzip' 138 reg['.cx'] = cx 139 reg['.cx1'] = cx 140 reg['.cx'] = new_cx 141 reg['.gz'] = gunzip 142 reg['.cx.gz'] = new_cx 143 reg['.cx1.gz'] = fail_cx 144 reg['.cx1'] = fail_cx 145 reg['.cx2'] = fail_cx 146 reg['new_cx'] = new_cx 147 148 # Two loaders associated with .cx 149 assert reg.lookup('hello.cx') == [new_cx,cx] 150 # Make sure the last loader applies first 151 assert reg.load('hello.cx') == 'new_cx' 152 # Make sure the next loader applies if the first fails 153 assert reg.load('hello.cx1') == 'cx' 154 # Make sure the format override works 155 assert reg.load('hello.cx1',format='.cx.gz') == 'new_cx' 156 # Make sure the format override works 157 assert reg.load('hello.cx1',format='new_cx') == 'new_cx' 158 # Make sure the case of all loaders failing is correct 159 try: reg.load('hello.cx2') 160 except CxError: pass # correct failure 161 else: raise AssertError,"Incorrect error on load failure" 162 # Make sure the case of no loaders fails correctly 163 try: reg.load('hello.missing') 164 except ValueError,msg: 165 assert str(msg)=="Unknown file type for hello.missing",'Message: <%s>'%(msg) 166 else: raise AssertError,"No error raised for missing extension" 167 assert reg.formats() == ['new_cx'] 168 assert reg.extensions() == ['.cx','.cx.gz','.cx1','.cx1.gz','.cx2','.gz'] 169 # make sure that it supports multiple '.' in filename 170 assert reg.load('hello.extra.cx1') == 'cx' 171 assert reg.load('hello.gz') == 'gunzip' 172 assert reg.load('hello.cx1.gz') == 'gunzip' # Since .cx1.gz fails 173 174 if __name__ == "__main__": test() 144 raise NoKnownLoaderException(e.message) # raise generic exception -
src/sas/sascalc/dataloader/loader.py
r463e7ffc r7f75a3f 1 1 """ 2 2 File handler to support different file extensions. 3 Uses reflectomet ry'sregistry utility.3 Uses reflectometer registry utility. 4 4 5 5 The default readers are found in the 'readers' sub-module … … 29 29 # Default readers are defined in the readers sub-module 30 30 import readers 31 from loader_exceptions import NoKnownLoaderException, FileContentsException 31 32 from readers import ascii_reader 32 33 from readers import cansas_reader 34 from readers import cansas_reader_HDF5 35 33 36 34 37 logger = logging.getLogger(__name__) … … 39 42 Readers and writers are supported. 40 43 """ 41 42 44 def __init__(self): 43 45 super(Registry, self).__init__() 44 46 45 # #Writers47 # Writers 46 48 self.writers = {} 47 49 48 # #List of wildcards50 # List of wildcards 49 51 self.wildcards = ['All (*.*)|*.*'] 50 52 51 # #Creation time, for testing53 # Creation time, for testing 52 54 self._created = time.time() 53 55 … … 63 65 of a particular reader 64 66 65 Defaults to the ascii (multi-column) reader 66 if no reader was registered for the file's 67 extension. 67 Defaults to the ascii (multi-column), cansas XML, and cansas NeXuS 68 readers if no reader was registered for the file's extension. 68 69 """ 69 70 try: 70 71 return super(Registry, self).load(path, format=format) 71 except: 72 try: 73 # No reader was found. Default to the ascii reader. 74 ascii_loader = ascii_reader.Reader() 75 return ascii_loader.read(path) 76 except: 77 cansas_loader = cansas_reader.Reader() 78 return cansas_loader.read(path) 72 except NoKnownLoaderException as e: 73 pass # try the ASCII reader 74 try: 75 ascii_loader = ascii_reader.Reader() 76 return ascii_loader.read(path) 77 except FileContentsException: 78 pass # try the cansas XML reader 79 try: 80 cansas_loader = cansas_reader.Reader() 81 return cansas_loader.read(path) 82 except FileContentsException: 83 pass # try the cansas NeXuS reader 84 try: 85 cansas_nexus_loader = cansas_reader_HDF5.Reader() 86 return cansas_nexus_loader.read(path) 87 except FileContentsException: 88 logging.errors("No default loader can load the data") 89 # No known reader available. Give up and throw an error 90 msg = "\n\tUnknown data format: %s.\n\tThe file is not a " % path 91 msg += "known format that can be loaded by SasView.\n" 92 msg += "Traceback:\n%s" % e.message 93 raise NoKnownLoaderException, msg 79 94 80 95 def find_plugins(self, dir): -
src/sas/sascalc/dataloader/readers/cansas_reader.py
r7432acb r7432acb 29 29 from sas.sascalc.dataloader.readers.xml_reader import XMLreader 30 30 from sas.sascalc.dataloader.readers.cansas_constants import CansasConstants, CurrentLevel 31 from sas.sascalc.dataloader.loader_exceptions import FileContentsException 31 32 32 33 # The following 2 imports *ARE* used. Do not remove either. … … 538 539 539 540 # Load in xml file and get the cansas version from the header 540 self.set_xml_file(xml_file) 541 from lxml import etree 542 try: 543 self.set_xml_file(xml_file) 544 except etree.XMLSyntaxError: 545 msg = "Cansas cannot load this file" 546 raise FileContentsException, msg 541 547 self.cansas_version = self.xmlroot.get("version", "1.0") 542 548 -
src/sas/sascalc/dataloader/readers/cansas_reader_HDF5.py
rc94280c r7f75a3f 13 13 TransmissionSpectrum, Detector 14 14 from sas.sascalc.dataloader.data_info import combine_data_info_with_plottable 15 from sas.sascalc.dataloader.loader_exceptions import FileContentsException 15 16 16 17 … … 75 76 if extension in self.ext or self.allow_all: 76 77 # Load the data file 77 self.raw_data = h5py.File(filename, 'r') 78 try: 79 self.raw_data = h5py.File(filename, 'r') 80 except Exception as e: 81 raise FileContentsException, e 78 82 # Read in all child elements of top level SASroot 79 83 self.read_children(self.raw_data, []) -
src/sas/sasgui/guiframe/local_perspectives/data_loader/data_loader.py
r235f514 r235f514 11 11 12 12 from sas.sascalc.dataloader.loader import Loader 13 from sas.sascalc.dataloader.loader_exceptions import NoKnownLoaderException 13 14 from sas.sasgui.guiframe.plugin_base import PluginBase 14 15 from sas.sasgui.guiframe.events import StatusEvent … … 41 42 APPLICATION_WLIST = config.APPLICATION_WLIST 42 43 44 43 45 class Plugin(PluginBase): 44 46 … … 56 58 """ 57 59 # menu for data files 58 menu_list = []59 60 data_file_hint = "load one or more data in the application" 60 61 menu_list = [('&Load Data File(s)', data_file_hint, self.load_data)] 61 62 gui_style = self.parent.get_style() 62 63 style = gui_style & GUIFRAME.MULTIPLE_APPLICATIONS 63 style1 = gui_style & GUIFRAME.DATALOADER_ON64 64 if style == GUIFRAME.MULTIPLE_APPLICATIONS: 65 65 # menu for data from folder … … 102 102 self.get_data(file_list) 103 103 104 105 104 def can_load_data(self): 106 105 """ … … 108 107 """ 109 108 return True 110 111 109 112 110 def _load_folder(self, event): … … 140 138 """ 141 139 if error is not None or str(error).strip() != "": 142 dial = wx.MessageDialog(self.parent, str(error), 'Error Loading File', 140 dial = wx.MessageDialog(self.parent, str(error), 141 'Error Loading File', 143 142 wx.OK | wx.ICON_EXCLAMATION) 144 143 dial.ShowModal() … … 149 148 """ 150 149 if os.path.isdir(path): 151 return [os.path.join(os.path.abspath(path), filename) for filename in os.listdir(path)] 150 return [os.path.join(os.path.abspath(path), filename) for filename 151 in os.listdir(path)] 152 152 153 153 def _process_data_and_errors(self, item, p_file, output, message): … … 178 178 for p_file in path: 179 179 basename = os.path.basename(p_file) 180 # Skip files that start with a period 181 if basename.startswith("."): 182 msg = "The folder included a potential hidden file - %s." \ 183 % basename 184 msg += " Do you wish to load this file as data?" 185 msg_box = wx.MessageDialog(None, msg, 'Warning', 186 wx.OK | wx.CANCEL) 187 if msg_box.ShowModal() == wx.ID_CANCEL: 188 continue 180 189 _, extension = os.path.splitext(basename) 181 190 if extension.lower() in EXTENSIONS: … … 213 222 info="info") 214 223 224 except NoKnownLoaderException as e: 225 logging.error(e.message) 226 self.load_update(output=None, message=e.message, info="warning") 227 self.load_complete(output=None, 228 message="Loading data failed!", 229 info="warning") 215 230 except: 216 231 logger.error(sys.exc_value) 217 232 218 error_message = "The Data file you selected could not be loaded.\n"219 error_message += " Make sure the content of your file"233 error_message = "The Data file you selected could not be " 234 error_message += "loaded.\nMake sure the content of your file" 220 235 error_message += " is properly formatted.\n" 221 236 error_message += "When contacting the SasView team, mention the" … … 223 238 error_message += "Error: " + str(sys.exc_info()[1]) 224 239 file_errors[basename] = [error_message] 225 self.load_update(output=output, message=error_message, info="warning") 240 self.load_update(output=output, message=error_message, 241 info="warning") 226 242 227 243 if len(file_errors) > 0: … … 236 252 237 253 self.load_complete(output=output, message="Loading data complete!", 238 info="info")254 info="info") 239 255 240 256 def load_update(self, output=None, message="", info="warning"): … … 245 261 wx.PostEvent(self.parent, StatusEvent(status=message, info=info, 246 262 type="progress")) 247 def load_complete(self, output, message="", error_message="", path=None, 248 info="warning"): 249 """ 250 post message to status bar and return list of data 251 """ 252 wx.PostEvent(self.parent, StatusEvent(status=message, 253 info=info, 263 264 def load_complete(self, output, message="", info="warning"): 265 """ 266 post message to status bar and return list of data 267 """ 268 wx.PostEvent(self.parent, StatusEvent(status=message, info=info, 254 269 type="stop")) 255 # if error_message != "":256 # self.load_error(error_message)257 270 self.parent.add_data(data_list=output)
Note: See TracChangeset
for help on using the changeset viewer.