Zwillingssterns Weltenwald
Published on Zwillingssterns Weltenwald (http://www.zwillingsstern.de)

Startseite > minimal Python script

minimal Python script

Over the years I found a few things which in my opinion are essential for any Python script:

  • A description,
  • useful logging
  • argument parsing and
  • doctests

Everything in this setup is low-overhead and available from Python 2.6 to 3.x, so you can use it to start any kind of project.

# encoding: utf-8

"""Minimal setup for a Python script.

No project should start without this.
"""

import argparse # for Python <2.6 use optparse
# setup sane logging. It tells you why, where and when something was
# logged, so you can jump to the source line right away.
import logging
logging.basicConfig(level=logging.WARNING,
                    format=' [%(levelname)-7s] (%(asctime)s) %(filename)s::%(lineno)d %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S')


def main():
    """The main entry point."""
    pass


# output test results as base60 number (for aesthetics)
def numtosxg(n):
    CHARACTERS = ('0123456789'
                  'ABCDEFGHJKLMNPQRSTUVWXYZ'
                  '_'
                  'abcdefghijkmnopqrstuvwxyz')
    s = ''
    if not isinstance(n, int) or n == 0:
        return '0'
    while n > 0:
        n, i = divmod(n, 60)
        s = CHARACTERS[i] + s
    return s


def _test():
    """  run doctests, can include setup. Complex example:
    >>> import sys
    >>> handlers = logging.getLogger().handlers # to stdout
    >>> logging.getLogger().handlers = []
    >>> logging.getLogger().addHandler(
    ...     logging.StreamHandler(stream=sys.stdout))
    >>> logging.warn("test logging")
    test logging
    >>> logging.getLogger().handlers = handlers
    """
    from doctest import testmod
    tests = testmod()
    if not tests.failed:
        return "^_^ ({})".format(numtosxg(tests.attempted))
    else: return ":( "*tests.failed

# keep argument setup and parsing together

parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("arguments", metavar="args", nargs="*",
                    help="Commmandline arguments")
parser.add_argument("--debug", action="store_true",
                    help="Set log level to debug")
parser.add_argument("--info", action="store_true",
                    help="Set log level to info")
parser.add_argument("--quiet", action="store_true",
                    help="Set log level to error")
parser.add_argument("--test", action="store_true",
                    help="Run tests")


# add a commandline switch to increase the log-level when running this
# script standalone. --test should run the tests.
if __name__ == "__main__":
    args = parser.parse_args()
    if args.debug:
        logging.getLogger().setLevel(logging.DEBUG)
    elif args.info:
        logging.getLogger().setLevel(logging.INFO)
    elif args.quiet:
        logging.getLogger().setLevel(logging.ERROR)
    if args.test:
        print(_test())
    else:
        main()
Werke von Arne Babenhauserheide. Lizensiert, wo nichts anderes steht, unter der GPLv3 or later und weiteren freien Lizenzen.

Diese Seite nutzt Cookies. Und Bilder. Manchmal auch Text. Eins davon muss ich wohl erwähnen — sagen die meisten anderen, und ich habe grade keine Zeit, Rechtstexte dazu zu lesen…


Source URL: http://www.zwillingsstern.de/english/free-software/minimal-python-script