Command-line programs · 4 / 15 Theory

Subcommands and exit codes

Tools like git group different actions into subcommands: git commit, git push, git log. Each one has its own arguments. argparse allows it with add_subparsers.

Defining subcommands

import argparse

parser = argparse.ArgumentParser(prog="text")
sub = parser.add_subparsers(dest="command", required=True)

sub.add_parser("upper")
sub.add_parser("stats")
rep = sub.add_parser("repeat")
rep.add_argument("times", type=int)

print(parser.parse_args(["upper"]))        # Namespace(command='upper')
print(parser.parse_args(["repeat", "3"]))  # Namespace(command='repeat', times=3)

dest="command" stores the name of the chosen subcommand and required=True forces one to be typed. Each subcommand has its own parser (rep) with the arguments it needs: times only exists in repeat.

Dispatching each subcommand to its function

A very clean pattern: each subcommand stores in func the function that runs it with set_defaults, and the program just calls args.func(args).

import argparse

def cmd_upper(args):
    print(args.text.upper())

def cmd_repeat(args):
    print(" ".join([args.text] * args.times))

parser = argparse.ArgumentParser(prog="text")
sub = parser.add_subparsers(dest="command", required=True)

p = sub.add_parser("upper")
p.add_argument("text")
p.set_defaults(func=cmd_upper)

p = sub.add_parser("repeat")
p.add_argument("text")
p.add_argument("times", type=int)
p.set_defaults(func=cmd_repeat)

args = parser.parse_args(["repeat", "hello", "3"])
args.func(args)   # hello hello hello

It is the outline of Text tool with subcommands, where the text arrives through standard input.

Exit codes

The exit code is the way a program tells whoever ran it whether it went well. Scripts and tools (for example, make, continuous integration or an if in bash) check it.

CodeUsual meaning
0success
1general error (something failed)
2incorrect usage (invalid arguments); it is the one argparse uses
othersmeanings specific to each program, documented

It is set with sys.exit(code). If the program ends without calling it, the code is 0. If you pass a text to sys.exit("message"), it writes it to standard error and ends with code 1.

import sys

def validate(password):
    problems = []
    if len(password) < 8:
        problems.append("too short")
    if not any(c.isdigit() for c in password):
        problems.append("no digit")
    return problems

for password in ("Secure123", "short"):
    problems = validate(password)
    try:
        if problems:
            sys.exit(1)
        sys.exit(0)
    except SystemExit as e:
        print(password, "->", e.code, problems)
# Secure123 -> 0 []
# short -> 1 ['too short', 'no digit']

That is Validator with exit code: the problems are shown and the program ends with 1 if there is any.

Error messages go to the error channel

Error messages go to sys.stderr, not to normal output. That way, if someone redirects the output to a file (python prog.py > result.txt), errors are still seen on screen and do not dirty the file.

import contextlib
import io
import sys

out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
    print("result: 42")
    print("warning: doubtful data", file=sys.stderr)

print(repr(out.getvalue()))   # 'result: 42\n'
print(repr(err.getvalue()))   # 'warning: doubtful data\n'

Reusing argparse errors

If you detect a usage problem that argparse cannot see by itself (for example, dividing by zero), call parser.error("message"): it writes the error in the standard format and ends with code 2, like it does with any invalid argument.

import argparse
import contextlib
import io

parser = argparse.ArgumentParser(prog="calc")
parser.add_argument("a", type=int)
parser.add_argument("b", type=int)
args = parser.parse_args(["7", "0"])

error = io.StringIO()
try:
    with contextlib.redirect_stderr(error):
        if args.b == 0:
            parser.error("cannot divide by zero")
except SystemExit as e:
    print("code:", e.code)                      # code: 2
print(error.getvalue().splitlines()[-1])        # calc: error: cannot divide by zero