For every simple Python script you need the same simple parts:
I’ve prepared a simple Python project with all these parts to use as a template. It is available on github.
Command-line arguments parsing is done in parse_arguments. The most interesting thing there is setting the default functions for submodules (and None for the main module). It looks like:
1first_module_parser.set_defaults(func=first_module)
and allows addressing the function needed by the chosen submodule as simply as
1if args.func:
2 args.func(args)
Logging initialization is simple and has only two modes: verbose (with the DEBUG level enabled) and non-verbose (only INFO messages):
1logging.basicConfig(
2 level=logging.DEBUG if args.verbose else logging.INFO,
3 format="[%(filename)s:%(lineno)d] %(levelname)-8s [%(asctime)s] %(message)s",
4 datefmt="%Y-%m-%d %H:%M:%S",
5)
There is also a Makefile in the project with simple compilation from Python code to a binary (python->cython->gcc->binary):
1cp python_template.py python_template.pyx
2cython *.pyx --embed
3gcc -Os -I /usr/include/python3.5m -o python_template python_template.c -lpython3.5m -lpthread -lm -lutil -ldl
4rm python_template.pyx python_template.c
The pytest test is located in a separate file test_python_template.py and may be invoked as:
1make test
Sample output:
1$ make test
2py.test test_python_template.py
3================================ test session starts =================================
4platform linux2 -- Python 2.7.12, pytest-2.8.7, py-1.4.31, pluggy-0.3.1
5rootdir: /home/bikulov/Projects/python_template, inifile:
6collected 3 items
7
8test_python_template.py ...
9
10============================== 3 passed in 0.01 seconds ==============================