forked from specpython/filespec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspecfile
executable file
·298 lines (236 loc) · 7.2 KB
/
specfile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
#!/usr/bin/env python
"""
****************
specfile
****************
Description
****************
Utility to handle data files in spec data format
Classes
****************
To check the definition of the spec data file format check `certif.com`_
.. _`certif.com`: http://www.certif.com/spec_help/scans.html
"""
version = "1.0"
from specpython.filespec import FileSpec
import os, sys, getopt
outformats = ['csv', 'tabs', 'spec']
def printUsage(msg=None, longmode=False):
if msg:
print msg
if not longmode:
print("""Usage: %(progname)s [options] filename [scanlist]
type \"%(progname)s -h\" for a detailed help """ % {'progname': sys.argv[0]} )
else:
print("""
Usage: %(progname)s [options] filename [scanlist]
Options are:
-f format
Format of the output files. Format can be one out of "tabs", "csv" or "spec"
Default output format is "tabs"
-O
Do not overwrite existing files. By default %(progname)s will overwrite existing files
if they have the same name
-S
Use single file for output. Useful particularly in the case of "spec" output format
-p prefix
Use `prefix` as prefix for output files
The default is to set prefix as the the root name of the original file
-s suffix
-d outdir
Use `outdir` directory to write output files. The default is to use the
root name of the original file.
-l
List scans in file in condensed mode
-L
List scans in file in non condensed mode
-a
Extract all scans in the file
-h
Prints this help and exits
-V
Prints program version
Specifying a scanlist:
scanlist can be given as a list of scan numbers or scan ranges (
using ":" to specify a specify first and last scan number in range.
Either "," or <space> can be used
to separate arguments.
Examples of valid scan specification are:
%(progname)s myfile.dat 3 6 8
%(progname)s myfile.dat 3,6,8
%(progname)s myfile.dat 3,6:12,37
%(progname)s myfile.dat 3 6:12 37
%(progname)s myfile.dat 3,6:12 37
Remember you can also use the "-a" flag to extract all scans in a file
""" % { 'progname': sys.argv[0]})
def parseScanArgs(scanarg):
args1 = scanarg.split()
args = []
for arg in args1:
args.extend( arg.split(",") )
scanlist = []
for arg in args:
if arg.find(":") != -1:
slist = None
try:
arg1, arg2 = arg.split(":")
iarg1 = int(arg1)
iarg2 = int(arg2)
if iarg2 <= iarg1:
raise "Bad scan arguments"
else:
slist = [ str(val) for val in range(iarg1, iarg2+1) ]
except:
raise "Bad scan arguments"
scanlist.extend(slist)
else:
iarg = arg
scanlist.append(iarg)
return scanlist
def formatScanList(scanlist, condensed=True):
strlist = ""
prev = -1
openlist = False
sep = ""
for scanno in scanlist:
if not condensed:
strlist += ( sep + str(scanno) )
else:
if scanno == (prev + 1):
openlist = True
else:
if openlist:
strlist += ":"
strlist += str(prev)
strlist += ( sep + str(scanno) )
openlist = False
prev = scanno
sep = ","
return strlist
def main():
outformat = "tabs"
suffix = None
prefix = None
outdir = None
overw_flag = False
single_flag = False
all_flag = False
list_flag = False
if len(sys.argv) < 2:
printUsage()
sys.exit(0)
try:
optlist, args = getopt.getopt(sys.argv[1:], "f:s:p:d:alLOShV")
except:
printUsage(msg="wrong usage")
sys.exit(1)
for o,a in optlist:
if o == '-h':
printUsage(longmode=True)
sys.exit(0)
elif o == '-V':
print version
sys.exit(0)
elif o == "-f":
outformat = a
elif o == '-p':
prefix = a
elif o == '-s':
suffix = a
elif o == '-d':
outdir = a
elif o == "-l":
list_flag = True
condensed = True
elif o == "-L":
list_flag = True
condensed = False
elif o == '-O':
overw_flag = True
elif o == '-a':
all_flag = True
elif o == '-S':
single_flag = True
if len(args) == 0:
printUsage("You should specify an input filename")
sys.exit(0)
if outformat not in outformats:
printUsage( msg="Wrong output format specified. Valid formats are %s" % ",".join(outformats))
sys.exit(1)
filename = args[0]
if len(args) > 1:
scanargs = " ".join( args[1:] )
else:
scanargs = None
# check if file exists and it is plain and readable file
if not os.path.exists(filename):
print("File %s does not exist." % filename)
sys.exit(1)
# open file. check if any scan could be indexed
try:
fs = FileSpec(filename)
except:
import traceback
traceback.print_exc()
print("Cannot index file %s." % filename)
sys.exit(1)
if len(fs) <= 0:
print("Cannot index file %s." % filename)
sys.exit(1)
if list_flag:
scanlist = [ scan.getNumber() for scan in fs ]
strlist = formatScanList( scanlist, condensed=condensed )
print strlist
sys.exit(0)
# prepare the scan list to extract
scanlist = None
if scanargs is not None:
#try:
scanlist = parseScanArgs( scanargs )
#except:
#print "Wrong scan selection"
#sys.exit(1)
scans = []
if scanlist:
for scanno in scanlist:
sparts = scanno.split(".")
sno = int(sparts[0])
if len(sparts) > 1:
sord = int(sparts[1])
else:
sord = 0
scan = fs.getScanByNumber( int(sno), int(sord) )
if scan:
scans.append( scan )
else:
print("Cannot find scan %d(%d) in file %s" % (sno,sord,filename))
else:
if all_flag:
# extract them all
scans = [ scan for scan in fs ]
inprefix = os.path.splitext( os.path.basename( filename ))[0]
if not outdir:
outdir = inprefix
if not suffix:
if outformat == "csv":
suffix = "csv"
else:
suffix = "dat"
if not prefix:
prefix = inprefix
if not os.path.exists(outdir):
os.makedirs(outdir)
for scan in scans:
if single_flag:
outfile = os.path.join( outdir, "%s_bundle.%s" % ( prefix, suffix ))
else:
outfile = os.path.join( outdir, "%s_%s.%s" % ( prefix, scan.getNumber(), suffix ))
# find alternative name if not set to overwrite
if not overw_flag and not single_flag:
tryno = 0
while os.path.exists(outfile):
tryno += 1
outfile = os.path.join( outdir, "%s_%s-%d.%s" % ( prefix, scan.getNumber(), tryno, suffix ))
scan.save(outfile, format=outformat, append=single_flag)
if __name__ == "__main__":
main()