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

I write a lot of small scripts in Python. This is the template that I use to start most of my scripts. This gets me started with good documentation, argument parsing, and error handling.

Python, 67 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
67
#!/usr/bin/env python
"""
SYNOPSIS

    TODO helloworld [-h,--help] [-v,--verbose] [--version]

DESCRIPTION

    TODO This describes how to use this script. This docstring
    will be printed by the script if there is an error or
    if the user requests help (-h or --help).

EXAMPLES

    TODO: Show some examples of how to use this script.

EXIT STATUS

    TODO: List exit codes

AUTHOR

    TODO: Name <name@example.org>

LICENSE

    This script is in the public domain, free from copyrights or restrictions.

VERSION

    $Id$
"""

import sys, os, traceback, optparse
import time
import re
#from pexpect import run, spawn

def main ():

    global options, args
    # TODO: Do something more interesting here...
    print 'Hello world!'

if __name__ == '__main__':
    try:
        start_time = time.time()
        parser = optparse.OptionParser(formatter=optparse.TitledHelpFormatter(), usage=globals()['__doc__'], version='$Id$')
        parser.add_option ('-v', '--verbose', action='store_true', default=False, help='verbose output')
        (options, args) = parser.parse_args()
        #if len(args) < 1:
        #    parser.error ('missing argument')
        if options.verbose: print time.asctime()
        main()
        if options.verbose: print time.asctime()
        if options.verbose: print 'TOTAL TIME IN MINUTES:',
        if options.verbose: print (time.time() - start_time) / 60.0
        sys.exit(0)
    except KeyboardInterrupt, e: # Ctrl-C
        raise e
    except SystemExit, e: # sys.exit()
        raise e
    except Exception, e:
        print 'ERROR, UNEXPECTED EXCEPTION'
        print str(e)
        traceback.print_exc()
        os._exit(1)

Everybody has their own version of this script, but if you don't have one then I think this is good starter for command-line scripts. Obviously no single template can be used to start every script.

There are TODO markers in the script so you will know what parts to fill in with your code. Most programming editors will highlight TODO tags.

Everything that you put into the docstring becomes the script's help page, so when you run the script with the '--help' option it will print the docstring and then exit. The docstring is patterned after a UNIX man page.

Argument and option parsing is done with optparse.

The entire main() function is wrapped in a try/except to handle any unexpected exceptions. The SystemExit handler is there to cleanly quit the script if sys.exit() is called anywhere in the script.

I use this with a Vim template system, so whenever I start a new Python script Vim will copy this template into the new buffer. I don't use any elaborate substitution template. TODO tags are good enough for me.

6 comments

Steven Bethard 16 years, 7 months ago  # | flag

optparse. You should really look at optparse in the stdlib. Seems like you're doing a lot more work than you have to here.

Ulf Rompe 16 years, 6 months ago  # | flag

Superfluous line. The first "if VERBOSE: print time.asctime()" will never print anything because VERBOSE is False by default and may be set to True in main() which is called in the next line.

Ulf Rompe 16 years, 6 months ago  # | flag

Wrong comment thread. Sorry, this comment should have gone to the top level.

Simon Tite 16 years, 4 months ago  # | flag

good starting template. As a complete and utter newbie to Python, this for me is a good starting point for starting a new script. I just hate starting from a completely blank piece of paper, don't you?

Noah Spurrier (author) 16 years, 3 months ago  # | flag

Now uses optparse. I switched it to optparse.

Noah Spurrier (author) 16 years, 3 months ago  # | flag

FIXED. Yep, I was doing the entire option parsing in the wrong function anyways. This is fixed.