Separate the application (oscopy_ipython) from the framework (oscopy)
[oscopy.git] / src / oscopy / writers / writer.py
blob2472c936294a1ebdd6957606706df71c60e3a9f1
1 """ Common signal export functions
2 """
4 import os.path
6 class WriteError(Exception):
7 """
8 Class WriteError -- Errors encountered when writing file
9 methods:
10 __init__(value)
11 Assign the error message
13 __str__()
14 Return a string with the error message
15 """
16 def __init__(self, msg):
17 """ Assign the error message
19 Parameter
20 ---------
21 msg: string
22 The error message
24 Returns
25 -------
26 WriteError
27 The object instanciated
28 """
29 self._msg = msg
31 def __str__(self):
32 """ Returns the error message
34 Parameter
35 ---------
36 None
38 Returns
39 -------
40 string
41 The error message
42 """
43 return self._msg
45 class Writer(object):
46 """ Writer -- Provide common function for exporting signals into files
47 The purpose of this class is to provide some basic functions to write the
48 Signals to files (file validation) thus simplifying the definition of
49 Writers for many different file formats.
51 The derived classes must redefine _get_format_name, _format_check and
52 write_signals.
53 """
54 def __init__(self):
55 """ Instanciate the Reader
57 Parameter
58 ---------
59 None
61 Returns
62 -------
63 Writer
64 The object instanciated
65 """
66 self._fn = ""
67 self._ow = False # Overwrite flag
68 self._opts = {} # Options passed to write()
70 def write(self, fn, sigs, opts = {}):
71 """ Do some checks before calling write_signals
73 Parameters
74 ----------
75 fn: string
76 Path to the output file
78 sigs: dict of Signals
79 List of Signals to write in the file
81 opts: dict of various data with strings as keys
82 Options to be considered for the writing
84 Returns
85 -------
86 bool
87 True if operation completed successfully
89 Raises
90 ------
91 WriteError
92 In case of invalid path or invalid file format
93 """
94 if isinstance(opts, dict):
95 self._opts = opts
96 # Overwrite option
97 if self._opts.has_key("ow"):
98 if self._opts["ow"] in ['True', 'true', '1']:
99 self._ow = True
100 else:
101 self._ow = False
102 if self._check(fn) and self._format_check(sigs):
103 return self.write_signals(sigs)
104 else:
105 return False
107 def _check(self, fn):
108 """ Common checks on file access
110 Parameter
111 ---------
112 fn: string
113 Path to the file to validate
115 Returns
116 -------
117 Nothing
119 Raises
120 ------
121 WriteError
122 In case no file is specified, file exist and overwrite is not allowed
123 or file access issue
125 if not (isinstance(fn, str) or isinstance(fn, unicode)):
126 raise WriteError("No string specified")
127 if not fn:
128 raise WriteError("No file specified")
129 if os.path.exists(fn):
130 if not self._ow:
131 self._fn = fn
132 raise WriteError("File already exist")
133 elif not os.path.isfile(fn):
134 raise WriteError("File exists but is not a file")
135 elif not os.access(fn, os.W_OK):
136 raise WriteError("Cannot access file")
137 elif not os.access(os.path.dirname(fn), os.W_OK):
138 raise WriteError("Cannot access destination directory")
139 self._fn = fn
140 return True
142 def _format_check(self, sigs):
143 """ Format specific checks, to be overridden by derived classes
145 Parameter
146 ---------
147 sigs: dict of Signals
148 The Signal list to write
150 Returns
151 -------
152 bool
153 True if no issue found to write the Signal list in this format
155 return False
157 def _get_format_name(self):
158 """ Return the format name
160 Parameter
161 ---------
162 None
164 Returns
165 -------
166 string
167 The format identifier
169 return None
171 def detect(self, format):
172 """ Return True if format format is supported
174 Parameter
175 ---------
176 format: string
177 Identifier of the whised format
179 Returns
180 -------
181 bool
182 True if this Writer manage this format
184 if (isinstance(format, str) or isinstance(format, unicode))\
185 and format == self._get_format_name():
186 return True
187 else:
188 return False
190 def write_signals(self, sigs):
191 """ Write Signals to file
192 This function must be redefined in the derived class
194 Parameter
195 ---------
196 sigs: dict of Signals
197 The list of Signals to write
199 Returns
200 -------
201 Nothing
203 return