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:

Use Node:

⚙ Babcom is trying to load the comments ⚙

This textbox will disappear when the comments have been loaded.

If the box below shows an error-page, you need to install Freenet with the Sone-Plugin or set the node-path to your freenet node and click the Reload Comments button (or return).

If you see something like Invalid key: There is no @ in that URI! (Sone/search.html), you need to setup Sone and the Web of Trust

If you had Javascript enabled, you would see comments for this page instead of the Sone page of the sites author.

Note: To make a comment which isn’t a reply visible to others here, include a link to this site somewhere in the text of your comment. It will then show up here. To ensure that I get notified of your comment, also include my Sone-ID.

Link to this site and my Sone ID: sone://6~ZDYdvAgMoUfG6M5Kwi7SQqyS-gTcyFeaNN1Pf3FvY

This spam-resistant comment-field is made with babcom.

Inhalt abgleichen
Willkommen im Weltenwald!

Beliebte Inhalte

Draketo neu: Beiträge

Ein Würfel System news