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
                    format=' [%(levelname)-7s] (%(asctime)s) %(filename)s::%(lineno)d %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S')

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

# output test results as base60 number (for aesthetics)
def numtosxg(n):
    CHARACTERS = ('0123456789'
    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:
    elif args.quiet:
    if args.test:
Inhalt abgleichen
Willkommen im Weltenwald!

Beliebte Inhalte news

Draketo neu: Beiträge