scripts

view bin/templates/unix-tool.py @ 111:a4403f37deec

Added a python template for building unix-style command line utilities.
author Matthias Friedrich <matt@mafr.de>
date Sat Oct 24 17:26:34 2009 +0200 (4 months ago)
parents
children
line source
1 #! /usr/bin/env python
2 #
3 # A template for building unix style command line utilities like head(1),
4 # nl(1), or cat(1).
5 #
6 import fileinput
7 import optparse
9 VERSION = '0.1.0'
12 # Set up the command line parser. Help (-h, --help) and version (--version)
13 # switches are already enabled. See http://docs.python.org/library/optparse.html
14 #
15 op = optparse.OptionParser(
16 usage='%prog [options] filenames...',
17 version='%prog ' + VERSION)
19 op.add_option('-l', '--list-filenames', action='store_true',
20 help="List filenames")
21 op.add_option('-n', '--number', action='store_true',
22 help="Print line numbers")
24 opts, args = op.parse_args()
27 # Iterate over all input files: If no file names are given on the command line,
28 # read from stdin. Otherwise iterate over all given files, with '-' being
29 # stdin. See http://docs.python.org/library/fileinput.html
30 #
31 for line in fileinput.input(args):
32 if opts.list_filenames and fileinput.isfirstline():
33 print "==>", fileinput.filename(), "<=="
35 if opts.number:
36 print "%d:%d: %s" % (fileinput.lineno(), fileinput.filelineno(), line),
37 else:
38 print line,
40 fileinput.close()
42 # EOF