Command-line programs · 5 / 15 Theory

Structuring a program and creating packages

A twenty-line script can be written straight through. A real program needs order: small functions, an entry function and, when it grows, several files organized in packages.

The main(argv) pattern

Put all the logic in functions and the entry point in a main function that receives the arguments as a parameter (argv=None means "use sys.argv"). That way main can be tested from other code without touching the terminal.

import argparse
import sys

def create_parser():
    parser = argparse.ArgumentParser(prog="grades")
    parser.add_argument("--min", type=int, default=0)
    parser.add_argument("--format", choices=["text", "csv"], default="text")
    return parser

def main(argv=None):
    args = create_parser().parse_args(argv)
    students = [("ana", 8), ("luis", 5), ("bea", 9)]
    passed = [s for s in students if s[1] >= args.min]
    if not passed:
        print("No results", file=sys.stderr)
        return 1
    for name, grade in sorted(passed):
        print(f"{name},{grade}" if args.format == "csv" else f"{name}: {grade}")
    return 0

# Tested without a terminal, passing the arguments:
code = main(["--min", "6", "--format", "csv"])
print("code:", code)
# ana,8
# bea,9
# code: 0

For the file to work as a program, it ends with the protected start:

# At the end of the file:
if __name__ == "__main__":
    sys.exit(main())

Note three details: main returns the code instead of calling sys.exit; sys.exit(main()) is protected by if __name__ == "__main__"; and errors go to sys.stderr. Apply all this in Complete program with main.

Modules and packages

A module is a .py file. A package is a folder of modules with an __init__.py file (it can be empty) that makes it importable.

# Structure of a project (files on disk)
#
# project/
# ├── pyproject.toml
# ├── README.md
# ├── src/
# │   └── grades/
# │       ├── __init__.py       # turns the folder into a package
# │       ├── __main__.py       # what runs with: python -m grades
# │       ├── cli.py            # argparse and main()
# │       └── calculations.py   # pure logic, no input/output
# └── tests/
#     └── test_calculations.py
  • Separate logic from the interface: calculations.py knows nothing about the terminal, so it is easy to test (and can be reused from a website or an application).
  • __init__.py can import whatever you want to expose: from .calculations import average lets you write from grades import average.
  • __main__.py lets you run the whole package with python -m grades.
  • Relative imports: inside a package, from .calculations import average imports a sibling module.

Distributing your program: pyproject.toml

The pyproject.toml file describes your project. With the [project.scripts] section, when it is installed a command appears with the name you choose.

# pyproject.toml
[project]
name = "grades"
version = "0.1.0"
description = "Grades report from the terminal"
requires-python = ">=3.10"
dependencies = []

[project.scripts]
grades = "grades.cli:main"      # when installed, the command exists: grades --min 6

[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"

Virtual environments and pip

A virtual environment is a folder with its own Python and its own libraries, so that each project has its own without interfering with the others. pip installs packages in it.

# In the terminal (not run here):
#
# python -m venv .venv                 # creates the environment in the .venv folder
# source .venv/bin/activate            # activates it (on Windows: .venv\Scripts\activate)
# pip install requests                 # installs a package from PyPI
# pip install -e .                     # installs YOUR project in editable mode
# pip freeze > requirements.txt        # saves the installed versions
# pip install -r requirements.txt      # reinstalls them on another machine
# deactivate                           # leaves the environment

Good practices

  • Use argparse (or an equivalent library) instead of reading sys.argv by hand.
  • Write a main(argv=None) that returns an exit code.
  • Errors go to sys.stderr and the program ends with a code other than 0.
  • Normal output must be easy for other programs to process (one line per item).
  • Write help (help=) and a short description: what is not documented is not used.
  • Keep logic separate from input/output so that it can be tested.
  • Each project in its own virtual environment, with its dependencies recorded.