User:Timothee Flutre/Notebook/Postdoc/2012/05/16

From OpenWetWare

Jump to: navigation, search
Project name Main project page
Previous entry      Next entry

Typical template for Python script

It is always rewarding on the long term to start any script with a minimum amount of generic code (verbose, command-line options, help message, license, etc). But it's a pain to write all this every time, right? So here is my typical template for any Python script:

   #!/usr/bin/env python
   
   # Author: Timothee Flutre
   # License: GPL-3
   # Aim: does this and that
   # help2man -o MyClass.man ./MyClass.py
   # groff -mandoc MyClass.man > MyClass.ps
   
   import sys
   import os
   import getopt
   import time
   import datetime
   import math
   
   
   class MyClass(object):
       
       def __init__(self):
           self.verbose = 1
           
           
       def help(self):
           msg = "`%s' does this and that.\n" % os.path.basename(sys.argv[0])
           msg += "\n"
           msg += "Usage: %s [OPTIONS] ...\n" % os.path.basename(sys.argv[0])
           msg += "\n"
           msg += "Options:\n"
           msg += " -h, --help\tdisplay the help and exit\n"
           msg += " -V, --version\toutput version information and exit\n"
           msg += " -v, --verbose\tverbosity level (0/default=1/2/3)\n"
           msg += "\n"
           msg += "Examples:\n"
           print msg; sys.stdout.flush()
           
           
       def version(self):
           msg = "%s 0.1\n" % os.path.basename(sys.argv[0])
           msg += "\n"
           msg += "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\n"
           msg += "This is free software; see the source for copying conditions.  There is NO\n"
           msg += "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
           print msg; sys.stdout.flush()
           
           
       def setAttributesFromCmdLine(self):
           try:
               opts, args = getopt.getopt( sys.argv[1:], "hVv:",
                                           ["help", "version", "verbose="])
           except getopt.GetoptError, err:
               sys.stderr.write("%s\n" % str(err))
               self.help()
               sys.exit(2)
           for o, a in opts:
               if o in ("-h", "--help"):
                   self.help()
                   sys.exit(0)
               elif o in ("-V", "--version"):
                   self.version()
                   sys.exit(0)
               elif o in ("-v", "--verbose"):
                   self.verbose = int(a)
               else:
                   assert False, "unhandled option"
                   
                   
       def checkAttributes(self):
           pass
       
       
       def run(self):
           self.checkAttributes()
           
           if self.verbose > 0:
               msg = "START %s" % time.strftime("%Y-%m-%d %H:%M:%S")
               startTime = time.time()
               print msg; sys.stdout.flush()
               
           # ... specific code ...
           
           if self.verbose > 0:
               msg = "END %s" % time.strftime("%Y-%m-%d %H:%M:%S")
               endTime = time.time()
               runLength = datetime.timedelta(seconds=
                                              math.floor(endTime - startTime))
               msg += " (%s)" % str(runLength)
               print msg; sys.stdout.flush()
               
               
   if __name__ == "__main__":
       i = MyClass()
       i.setAttributesFromCmdLine()
       i.run()



Personal tools