Python program template

For every simple python script you need same simple parts:

  • command line arguments parsing
  • logging
  • [optional] submodules
  • [optional] building to a binary

I’ve prepared a simple python project with all these parts to use as template. It is available on github.

Command line arguments parsing is done in parse_arguments. The most interesting thing there is setting default fuctions for submodules (and None for main module). It looks like:


and allows to address needed by chosen submodule function as simple as

if args.func:

Logging initialization is simple and has only two modes: verbose (with DEBUG level enabled) and non-verbose (only INFO messages):

    level=logging.DEBUG if args.verbose else logging.INFO,
    format="[%(filename)s:%(lineno)d] %(levelname)-8s [%(asctime)s]  %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",

These is also a Makefile in the project with simple compilation from python code to binary (python->cython->gcc->binary):

cp python_template.pyx
cython *.pyx --embed
gcc -Os -I /usr/include/python3.5m -o python_template python_template.c -lpython3.5m -lpthread -lm -lutil -ldl
rm python_template.pyx python_template.c

pytest test is located in the separate file and may be invoced as:

make test

Sample output:

$ make test
================================ test session starts =================================
platform linux2 -- Python 2.7.12, pytest-2.8.7, py-1.4.31, pluggy-0.3.1
rootdir: /home/bikulov/Projects/python_template, inifile:
collected 3 items ...

============================== 3 passed in 0.01 seconds ==============================