]> git.donarmstrong.com Git - biopieces.git/blob - code_python/Cjung/Args.py
fixed seq qual length check
[biopieces.git] / code_python / Cjung / Args.py
1 """
2 Handling of arguments: options, arguments, file(s) content iterator
3
4 For small scripts that:
5 - read some command line options
6 - read some command line positional arguments
7 - iterate over all lines of some files given on the command line, or stdin if none given
8 - give usage message if positional arguments are missing
9 - give usage message if input files are missing and stdin is not redirected
10 """
11
12 __author__ = 'Peter Kleiweg'
13 __version__ = '0.2'
14 __date__ = '2004/08/28'
15
16 import os, sys, getopt
17
18 class Args:
19         """
20         Perform common tasks on command line arguments
21         
22         Instance data:
23         progname (string) -- name of program
24         opt (dictionary) -- options with values
25         infile (string) -- name of current file being processed
26         lineno (int) -- line number of last line read in current file
27         linesum (int) -- total of lines read
28         """
29
30         def __init__(self, usage='Usage: %(progname)s [opt...] [file...]'):
31                 "init, usage string: embed program name as %(progname)s"
32                 self.progname = os.path.basename(sys.argv[0])
33                 self.opt = {}
34                 self.infile = None
35                 self.lineno = 0
36                 self.linesum = 0
37                 self._argv = sys.argv[1:]
38                 self._usage = usage
39
40         def __iter__(self):
41                 "iterator: set-up"
42                 if self._argv:
43                         self.infile = self._argv.pop(0)
44                         self._in = open(self.infile, 'r')
45                         self._stdin = False
46                 else:
47                         if sys.stdin.isatty():
48                                 print "### USAGE in __iter__"
49                                 #self.usage()  # Doesn't return
50                                 return None
51                         self.infile = '<stdin>'
52                         self._in = sys.stdin
53                         self._stdin = True
54                 return self
55
56         def next(self):
57                 "iterator: get next line, possibly from next file"
58                 while True:
59                         line = self._in.readline()
60                         if line:
61                                 self.lineno += 1
62                                 self.linesum += 1
63                                 return line
64
65                         if self._stdin:
66                                 break
67
68                         self._in.close()
69                         try:
70                                 self.infile = self._argv.pop(0)
71                         except IndexError:
72                                 break
73                         self.lineno = 0
74                         self._in = open(self.infile, 'r')
75
76                 self.lineno = -1
77                 self.infile = None
78                 raise StopIteration
79
80         def getopt(self, shortopts, longopts=[]):
81                 "get options and merge into dict 'opt'"
82                 try:
83                         options, self._argv = getopt.getopt(self._argv, shortopts, longopts)
84                 except getopt.GetoptError:
85                         print "### USAGE in getopt"
86                         #self.usage()
87                         return None
88                 self.opt.update(dict(options))
89
90         def shift(self):
91                 "pop first of remaining arguments (shift)"
92                 try:
93                         return self._argv.pop(0)
94                 except IndexError:
95                         #print "### USAGE in shift"
96                         #self.usage()
97                         return None
98
99
100         def pop(self):
101                 "pop last of remaining arguments"
102                 try:
103                         return self._argv.pop()
104                 except IndexError:
105                         print "### USAGE in pop"
106                         #self.usage()
107                         return None
108
109         def warning(self, text):
110                 "print warning message to stderr, possibly with filename and lineno"
111                 if self.lineno > 0:
112                         print >> sys.stderr, '%s:%i: warning: %s' % (self.infile, self.lineno, text)
113                 else:
114                         print >> sys.stderr, '\nWarning %s: %s\n' % (self.progname, text)
115
116         def error(self, text):
117                 "print error message to stderr, possibly with filename and lineno, and exit"
118                 if self.lineno > 0:
119                         print >> sys.stderr, '%s:%i: %s' % (self.infile, self.lineno, text)
120                 else:
121                         print >> sys.stderr, '\nError %s: %s\n' % (self.progname, text)
122                 sys.exit(1)
123
124         def usage(self):
125                 "print usage message, and exit"
126                 print >> sys.stderr
127                 print >> sys.stderr, self._usage % {'progname': self.progname}
128                 print >> sys.stderr        
129                 #sys.exit(1)
130
131
132 if __name__ == '__main__':
133
134         a = Args('Usage: %(progname)s [-a value] [-b value] [-c] word [file...]')
135
136         a.opt['-a'] = 'option a'    # set some default option values
137         a.opt['-b'] = 'option b'    #
138         a.getopt('a:b:c')           # get user supplied option values
139
140         word = a.shift()            # get the first of the remaining arguments
141                                                                 # use a.pop() to get the last instead
142
143         for line in a:              # iterate over the contents of all remaining arguments (file names)
144                 if a.lineno == 1:
145                         print 'starting new file:', a.infile
146                 a.warning(line.rstrip())
147
148         print 'Options:', a.opt
149         print 'Word:', word
150         print 'Total number of lines:', a.linesum
151
152         print 'Command line:', sys.argv     # unchanged
153
154         a.warning('warn 1')         # print a warning
155         a.error('error')            # print an error message and exit
156         a.warning('warn 2')         # this won't show
157