Welcome, guest | Sign In | My Account | Store | Cart

This skeleton is a good start for well behaved unix command line tools. The module optparse is used to get arguments and options and to print usage and help. Like typical unix tools with one or two file arguments it handles stdin and stdout if not enough arguments are given.

Python, 66 lines
 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
#! /usr/bin/env python
from optparse import OptionParser
import os,sys

doc=""" 
%prog [Options] [inputfile [outputfile]]
"""

#import re
#regexStr = ''
#regex = re.compile(regexStr)

lines = []

def processLine(line):
#    result = line.strip().split(':')
#     match = regex.match(line)
#    if match:
#        result = match.groups() 
    result = line.rstrip()
    lines.append(result)
    
def main():
    global options
    parser = OptionParser(version="%prog 0.0", usage=doc)
    parser.add_option("-o", "--logfile", dest="logfilename",
                      help="write log to FILE", metavar="FILE")
    parser.add_option("-q", "--quiet",
                      action="store_false", dest="verbose", default=True,
                      help="don't print status messages to stdout")
    parser.add_option("-d", "--debug",
                      action="store_true", dest="debug", default=False,
                      help="print debug information")
    (options, args) = parser.parse_args()
    input = None    
    if len(args) <= 2:
        if len(args) > 0 and args[0] != '-':
            input = open(args[0], 'r')
    if not input:
       if options.debug: print >> sys.stderr, 'reading input from stdin'
       input = sys.stdin        
        
    if len(args) == 2: sys.stdout = open(args[1], 'w')

    if options.logfilename: options.logfile = open(options.logfilename, 'w')
    else:                   options.logfile = None

    if options.debug:
        print >> sys.stderr, "options:", options
        print >> sys.stderr, "args   :", args

#    lscmd = 'ls -lrt '
#    input = os.popen(lscmd).readlines()

    for line in input:
        processLine(line)
            
    for line in lines:
        if options.verbose:
            print line
    if options.verbose: print >> sys.stderr, '%d lines' % len(lines)
    if options.logfile: print >> options.logfile, '%d lines' % len(lines)
    sys.exit(0)
       
if __name__ == '__main__':
    main() 

If I need a tiny utility for crunching text files or the output of a program I begin with this skeleton source, throw out what I don't need and put the special handling in the processLine() function. If more options are needed I copy&paste a similar add_option().

The optparse module gives you the usage for free:

unixtool_skeleton.py -h

Usage: unixtool_skeleton.py [Options] [inputfile [outputfile]]

Options: --version show program's version number and exit -h, --help show this help message and exit -o FILE, --logfile=FILE write log to FILE -q, --quiet don't print status messages to stdout -d, --debug print debug information

2 comments

Steven Bethard 16 years, 6 months ago  # | flag

try argparse. Note that the argparse module (http://argparse.python-hosting.com/) provides builtin support for some of the positional argument work you're doing manually:

parser = argparse.ArgumentParser(version="%(prog)s 0.0")
parser.add_argument("-o", "--logfile", dest="logfilename",
                    help="write log to FILE", metavar="FILE")
parser.add_argument("-q", "--quiet",
                    action="store_false", dest="verbose", default=True,
                    help="don't print status messages to stdout")
parser.add_argument("-d", "--debug",
                    action="store_true", dest="debug", default=False,
                    help="print debug information")
parser.add_argument('inputfile', nargs='?', type=argparse.FileType('r'),
                    default=sys.stdin)
parser.add_argument('outputfile', nargs='?', type=argparse.FileType('w'),
                    default=sys.stdout)
options = parser.parse_args()

Then you just use options.inputfile and options.outputfile like you currently use input and output -- no need to fiddle around with the "args" list.

rbenegal kumar 15 years, 8 months ago  # | flag

You should also add a signal trap (in case person enters ^c or kills. Thanks, anyway, I shall start usin g this. optparse looks similar to the argparse mentioned by Steven Bethard.