Python program template

2019-02-22
#python

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:

first_module_parser.set_defaults(func=first_module)

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

if args.func:
    args.func(args)

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

logging.basicConfig(
    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.py 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 test_python_template.py and may be invoced as:

make test

Sample output:

$ make test
py.test test_python_template.py
================================ 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

test_python_template.py ...

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