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

From OpenWetWare

(Difference between revisions)
Jump to: navigation, search
(Entry title: first version)
(Typical template for Python script: add input attribute + example of error message)
Line 30: Line 30:
         def __init__(self):
         def __init__(self):
             self.verbose = 1
             self.verbose = 1
 +
            self.input = ""
              
              
              
              
Line 41: Line 42:
             msg += " -V, --version\toutput version information and exit\n"
             msg += " -V, --version\toutput version information and exit\n"
             msg += " -v, --verbose\tverbosity level (0/default=1/2/3)\n"
             msg += " -v, --verbose\tverbosity level (0/default=1/2/3)\n"
 +
            msg += " -i\tinput"
             msg += "\n"
             msg += "\n"
             msg += "Examples:\n"
             msg += "Examples:\n"
Line 57: Line 59:
         def setAttributesFromCmdLine(self):
         def setAttributesFromCmdLine(self):
             try:
             try:
-
                 opts, args = getopt.getopt( sys.argv[1:], "hVv:",
+
                 opts, args = getopt.getopt( sys.argv[1:], "hVv:i:",
                                             ["help", "version", "verbose="])
                                             ["help", "version", "verbose="])
             except getopt.GetoptError, err:
             except getopt.GetoptError, err:
Line 72: Line 74:
                 elif o in ("-v", "--verbose"):
                 elif o in ("-v", "--verbose"):
                     self.verbose = int(a)
                     self.verbose = int(a)
 +
                elif o in ("-i"):
 +
                    self.input = a
                 else:
                 else:
                     assert False, "unhandled option"
                     assert False, "unhandled option"
Line 77: Line 81:
                      
                      
         def checkAttributes(self):
         def checkAttributes(self):
-
             pass
+
             if self.input == "":
-
       
+
                msg = "ERROR: missing required argument -i"
-
       
+
                sys.stderr.write("%s\n\n" % msg)
 +
              self.help()
 +
              sys.exit(1)
 +
             
 +
             
         def run(self):
         def run(self):
             self.checkAttributes()
             self.checkAttributes()

Revision as of 11:10, 16 May 2012

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
           self.input = ""
           
           
       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 += " -i\tinput"
           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:i:",
                                           ["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)
               elif o in ("-i"):
                    self.input = a
               else:
                   assert False, "unhandled option"
                   
                   
       def checkAttributes(self):
           if self.input == "":
               msg = "ERROR: missing required argument -i"
               sys.stderr.write("%s\n\n" % msg)
              self.help()
              sys.exit(1)
              
              
       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