2 Handling of arguments: options, arguments, file(s) content iterator
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
12 __author__ = 'Peter Kleiweg'
14 __date__ = '2004/08/28'
16 import os, sys, getopt
20 Perform common tasks on command line arguments
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
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])
37 self._argv = sys.argv[1:]
43 self.infile = self._argv.pop(0)
44 self._in = open(self.infile, 'r')
47 if sys.stdin.isatty():
48 print "### USAGE in __iter__"
49 #self.usage() # Doesn't return
51 self.infile = '<stdin>'
57 "iterator: get next line, possibly from next file"
59 line = self._in.readline()
70 self.infile = self._argv.pop(0)
74 self._in = open(self.infile, 'r')
80 def getopt(self, shortopts, longopts=[]):
81 "get options and merge into dict 'opt'"
83 options, self._argv = getopt.getopt(self._argv, shortopts, longopts)
84 except getopt.GetoptError:
85 print "### USAGE in getopt"
88 self.opt.update(dict(options))
91 "pop first of remaining arguments (shift)"
93 return self._argv.pop(0)
95 #print "### USAGE in shift"
101 "pop last of remaining arguments"
103 return self._argv.pop()
105 print "### USAGE in pop"
109 def warning(self, text):
110 "print warning message to stderr, possibly with filename and lineno"
112 print >> sys.stderr, '%s:%i: warning: %s' % (self.infile, self.lineno, text)
114 print >> sys.stderr, '\nWarning %s: %s\n' % (self.progname, text)
116 def error(self, text):
117 "print error message to stderr, possibly with filename and lineno, and exit"
119 print >> sys.stderr, '%s:%i: %s' % (self.infile, self.lineno, text)
121 print >> sys.stderr, '\nError %s: %s\n' % (self.progname, text)
125 "print usage message, and exit"
127 print >> sys.stderr, self._usage % {'progname': self.progname}
132 if __name__ == '__main__':
134 a = Args('Usage: %(progname)s [-a value] [-b value] [-c] word [file...]')
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
140 word = a.shift() # get the first of the remaining arguments
141 # use a.pop() to get the last instead
143 for line in a: # iterate over the contents of all remaining arguments (file names)
145 print 'starting new file:', a.infile
146 a.warning(line.rstrip())
148 print 'Options:', a.opt
150 print 'Total number of lines:', a.linesum
152 print 'Command line:', sys.argv # unchanged
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