February 2010 (1)
September 2009 (1)
May 2009 (1)
April 2009 (1)
March 2009 (4)
January 2009 (3)
November 2008 (2)
October 2008 (2)
September 2008 (1)
August 2008 (5)
July 2008 (3)
June 2008 (1)
May 2008 (5)
April 2008 (8)
March 2008 (3)
February 2008 (1)
January 2008 (2)
December 2007 (2)
November 2007 (4)
October 2007 (17)
September 2007 (9)
2009-03-03 15:55:46
Had a burst of hacking over the weekend, and one of the outcomes was the realisation that I have a few practises that could be usefully put into a template for new scripts.
So: here is my current starting point for any new script.
#!/usr/bin/python
# -*- coding: utf-8 -*-
from optparse import OptionParser
def _test():
import doctest
doctest.testmod()
def _profile_main(filename):
import cProfile, pstats
prof = cProfile.Profile()
ctx = """_main(filename)"""
prof = prof.runctx(ctx, globals(), locals())
stats = pstats.Stats(prof)
stats.sort_stats("time")
stats.print_stats(10)
def _blurt(s):
pass
def _main(filename):
pass
if __name__ == "__main__":
usage = "usage: %prog [options]"
parser = OptionParser(usage=usage)
parser.add_option('--profile', '-P',
help = "Print out profiling stats",
action = 'store_true')
parser.add_option('--test', '-t',
help ='Run doctests',
action = 'store_true')
parser.add_option('--verbose', '-v',
help ='print debugging output',
action = 'store_true')
(options, args) = parser.parse_args()
# assign non-flag arguments here
# filename = args[0]
def really_blurt(s):
print s
if options.verbose:
_blurt = really_blurt
if options.profile:
_profile_main(filename)
exit()
if options.test:
_blurt = really_blurt
_test()
exit()
_main()
Rendered at 2010-03-12 11:50:43
From Julian on 2009-03-05 10:57:33
I quite like returning a code from main such that you can do something like: sys.exit(_main()) or sys.exit(_main() or 0) in case you’re lazy and don’t return anything. (Nicked shamelessly from the comments at http://www.artima.com/weblogs/viewpost.jsp?thread=4829 )