Return to Snippet

Revision: 5640
at March 21, 2008 08:29 by pulczynski


Updated Code
#!/usr/bin/env python
# -*- coding: utf-8 -*

u"""Program name - short description

Example usage
=============

.. sourcecode:: bash

    python program_name.py -vvvvv action

:author: `Name Surname <mailto:[email protected]>`__
"""

# Pylint checks
# "line to long" pylint: disable-msg=C0301
# "Used * or ** magic" pylint: disable-msg=W0142

__revision__ = "$Id$"
__docformat__ = 'restructuredtext en'

import os, sys, logging, optparse

#: Glogbal logger instance
LOG = logging.getLogger(__name__)
#: Debug level names as a string
LOG_HELP = ','.join(["%d=%s" % (4-x, logging.getLevelName((x+1)*10)) for x in xrange(5)])
#: Console LOG format
LOG_FORMAT_CONS = '%(asctime)s %(name)-12s %(levelname)8st%(message)s'
#: File LOG format
LOG_FORMAT_FILE = '%(asctime)s %(name)s[%(process)d] %(levelname)10s %(message)s'
#: Levels of logging translation (count of -v, log level)
LOGLEVEL_DICT = { 1 : 50, 2:40, 3:20, 4:10, 5:1 }

DEFAULT_VERBOSITY = 0


def default_action():             
    """ Does foo and bar """
    LOG.info("Default action done")

def main():
    """ Main function - parses args and runs action """
    parser = optparse.OptionParser(usage="%prog or type %prog -h (--help) for help", description=__doc__, version="%prog" + __revision__)
    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)
    parser.add_option("-l", "--logfile", dest="logfile",    default = None, help = "Log to file instead off console [default: %default]" )

    (options, args) = parser.parse_args()

    verbosity = LOGLEVEL_DICT.get(int(options.verbosity), DEFAULT_VERBOSITY)

    # Set up logging
    if options.logfile is None:
        logging.basicConfig(level=verbosity, format=LOG_FORMAT_CONS)
    else:
        logfilename = os.path.normpath(options.logfile)
        logging.basicConfig(level=verbosity, format=LOG_FORMAT_FILE, filename=logfilename, filemode='a')
        print >> sys.stderr, "Logging to %s" % logfilename

    # Run actions
    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())

    for action in args:     
        if action == 'raise':
            raise Exception("User requested exception")
        else:
            default_action()
            
    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())

if __name__ == "__main__":
    main()

Revision: 5639
at March 21, 2008 08:07 by pulczynski


Initial Code
#!/usr/bin/env python
# -*- coding: utf-8 -*

u"""Program name - short description

Example usage
=============

.. sourcecode:: bash

    python program_name.py -vvvvv action

:author: `Name Surname <mailto:[email protected]>`__
"""

# Pylint checks
# "line to long" pylint: disable-msg=C0301
# "Used * or ** magic" pylint: disable-msg=W0142

__revision__ = "$Id$"
__docformat__ = 'restructuredtext en'

import os, sys, logging, optparse

#: Glogbal logger instance
LOG = logging.getLogger(__name__)
#: Debug level names as a string
LOG_HELP = ','.join(["%d=%s" % (4-x, logging.getLevelName((x+1)*10)) for x in xrange(5)])
#: Console LOG format
LOG_FORMAT_CONS = '%(asctime)s %(name)-12s %(levelname)8st%(message)s'
#: File LOG format
LOG_FORMAT_FILE = '%(asctime)s %(name)s[%(process)d] %(levelname)10s %(message)s'
#: Levels of logging translation (count of -v, log level)
LOGLEVEL_DICT = { 1 : 50, 2:40, 3:20, 4:10, 5:1 }

DEFAULT_VERBOSITY = 0


def default_action():             
    """ Does foo and bar """
    LOG.info("Default action done")

def main():
    """ Main function - parses args and runs action """
    parser = optparse.OptionParser(usage="%prog or type %prog -h (--help) for help", description=__doc__, version="%prog" + __revision__)
    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)
    parser.add_option("-l", "--logfile", dest="logfile",    default = None, help = "Log to file instead off console [default: %default]" )

    (options, args) = parser.parse_args()

    verbosity = LOGLEVEL_DICT.get(int(options.verbosity), DEFAULT_VERBOSITY)

    # Set up logging
    if options.logfile is None:
        logging.basicConfig(level=verbosity, format=LOG_FORMAT_CONS)
    else:
        logfilename = os.path.normpath(options.logfile)
        logging.basicConfig(level=verbosity, format=LOG_FORMAT_FILE, filename=logfilename, filemode='a')
        print >> sys.stderr, "Logging to %s" % logfilename

    # Run actions
    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())

    for action in args:     
        if action == 'raise':
            raise Exception("User requested exception")
        else:
            default_action()
            
    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())

if __name__ == "__main__":
    main()

Initial URL

                                

Initial Description

                                

Initial Title
Python console application template with logging and option parsing.

Initial Tags
textmate, python

Initial Language
Python