Posted By

pulczynski on 03/21/08


Tagged

textmate python optparse logging docstring restructuredtext rst


Versions (?)


Advertising

Website Promotion DIRECTORY is a crucial factor for all websites that need to gain better organic search engine rankings and increase website traffic.
Submitting your website as part of your Web Promotion strategy to our SEO friendly and high traffic Business Directory for review is an excellent way to gain a valuable backlink and increase your websites visibility online.

Submit Site


Who likes this?

4 people have marked this snippet as a favorite

pulczynski
ntamas
georg
vasilije


Python console application template with logging and option parsing.


Published in: Python 






Expand | Embed | Plain Text
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*
  3.  
  4. u"""Program name - short description
  5.  
  6. Example usage
  7. =============
  8.  
  9. .. sourcecode:: bash
  10.  
  11. python program_name.py -vvvvv action
  12.  
  13. :author: `Name Surname <mailto:foo@example.com>`__
  14. """
  15.  
  16. # Pylint checks
  17. # "line to long" pylint: disable-msg=C0301
  18. # "Used * or ** magic" pylint: disable-msg=W0142
  19.  
  20. __revision__ = "$Id$"
  21. __docformat__ = 'restructuredtext en'
  22.  
  23. import os, sys, logging, optparse
  24.  
  25. #: Glogbal logger instance
  26. LOG = logging.getLogger(__name__)
  27. #: Debug level names as a string
  28. LOG_HELP = ','.join(["%d=%s" % (4-x, logging.getLevelName((x+1)*10)) for x in xrange(5)])
  29. #: Console LOG format
  30. LOG_FORMAT_CONS = '%(asctime)s %(name)-12s %(levelname)8st%(message)s'
  31. #: File LOG format
  32. LOG_FORMAT_FILE = '%(asctime)s %(name)s[%(process)d] %(levelname)10s %(message)s'
  33. #: Levels of logging translation (count of -v, log level)
  34. LOGLEVEL_DICT = { 1 : 50, 2:40, 3:20, 4:10, 5:1 }
  35.  
  36. DEFAULT_VERBOSITY = 0
  37.  
  38.  
  39. def default_action():
  40. """ Does foo and bar """
  41. LOG.info("Default action done")
  42.  
  43. def main():
  44. """ Main function - parses args and runs action """
  45. parser = optparse.OptionParser(usage="%prog or type %prog -h (--help) for help", description=__doc__, version="%prog" + __revision__)
  46. parser.add_option("-v", action="count", dest="verbosity", default = DEFAULT_VERBOSITY, help = "Verbosity. Add more -v to be more verbose (%s) [default: %%default]" % LOG_HELP)
  47. parser.add_option("-l", "--logfile", dest="logfile", default = None, help = "Log to file instead off console [default: %default]" )
  48.  
  49. (options, args) = parser.parse_args()
  50.  
  51. verbosity = LOGLEVEL_DICT.get(int(options.verbosity), DEFAULT_VERBOSITY)
  52.  
  53. # Set up logging
  54. if options.logfile is None:
  55. logging.basicConfig(level=verbosity, format=LOG_FORMAT_CONS)
  56. else:
  57. logfilename = os.path.normpath(options.logfile)
  58. logging.basicConfig(level=verbosity, format=LOG_FORMAT_FILE, filename=logfilename, filemode='a')
  59. print >> sys.stderr, "Logging to %s" % logfilename
  60.  
  61. # Run actions
  62. LOG.info("Starting %s, rev %s from %s using verbosity %s/%s as PID %d", __name__, __revision__, os.path.abspath(__file__), options.verbosity, verbosity, os.getpid())
  63.  
  64. for action in args:
  65. if action == 'raise':
  66. raise Exception("User requested exception")
  67. else:
  68. default_action()
  69.  
  70. LOG.info("Exited %s, rev %s from %s using verbosity %s/%s as PID %d", __name__, __revision__, os.path.abspath(__file__), options.verbosity, verbosity, os.getpid())
  71.  
  72. if __name__ == "__main__":
  73. main()

Report this snippet 

You need to login to post a comment.

Download royalty free graphics