Sub topic 8
Writing useful help and usage text
This chapter assumes you can build a parser with positional arguments, options and flags, and that you know the main(argv) pattern from earlier chapters. It covers how argparse builds --help output, how to control each part of it, and how to check that it works.
What argparse generates for you
Every ArgumentParser adds a -h / --help option unless you pass add_help=False. When a user runs it, argparse prints the help text to stdout and exits with status 0. Help is a successful answer to a request, so it goes to stdout and the exit status is 0.
Usage errors are different. A wrong or missing argument prints the short usage line plus an error message to stderr and exits with status 2.
The full help message has up to five parts. The usage line and the argument sections are generated from your add_argument calls. You supply the description and the epilog.
A complete example
This program uses most of the tools in this chapter.
import argparse
class HelpFormatter(argparse.ArgumentDefaultsHelpFormatter,
argparse.RawDescriptionHelpFormatter):
"""Show defaults and keep the line breaks in description and epilog."""
def build_parser():
parser = argparse.ArgumentParser(
prog="resize",
description="Resize images.\n\nReads each FILE and writes a scaled copy.",
epilog="Example:\n resize --width 800 photo.jpg",
formatter_class=HelpFormatter,
)
parser.add_argument("files", nargs="+", metavar="FILE",
help="image files to resize")
parser.add_argument("-w", "--width", type=int, default=640,
metavar="PIXELS", help="target width")
parser.add_argument("--debug", action="store_true",
help=argparse.SUPPRESS)
parser.add_argument("--version", action="version",
version="%(prog)s 1.2")
return parser
def main(argv=None):
args = build_parser().parse_args(argv)
for name in args.files:
print(f"{name} -> {args.width}px")
return 0
if __name__ == "__main__":
raise SystemExit(main())Running python resize.py --help prints output like this:
usage: resize [-h] [-w PIXELS] [--version] FILE [FILE ...]
Resize images.
Reads each FILE and writes a scaled copy.
positional arguments:
FILE image files to resize
options:
-h, --help show this help message and exit
-w PIXELS, --width PIXELS
target width (default: 640)
--version show program's version number and exit
Example:
resize --width 800 photo.jpgPython 3.9 and earlier print optional arguments: instead of options:. Line wrapping depends on the terminal width, which argparse reads from the terminal or the COLUMNS environment variable.
The help string
The help= argument is the one-line explanation shown next to each option. Good help strings follow a few rules:
- Describe what the value does, not how the code uses it. "target width" is better than "sets args.width".
- Keep it short. Argparse re-wraps the text to fit the terminal and collapses your newlines and extra spaces.
- Do not repeat the option name. The reader can already see
--width.
A help string can contain %(name)s placeholders. Argparse fills them in from the argument's attributes when it prints help.
| Placeholder | Expands to |
|---|---|
| `%(prog)s` | The program name |
| `%(default)s` | The argument's default value |
| `%(choices)s` | The allowed values, joined with commas |
| `%(type)s` | The name of the type callable |
| `%(metavar)s` | The placeholder name shown in usage |
| `%(dest)s` | The attribute name on the result |
parser.add_argument("--level", choices=["debug", "info"], default="info",
help="log level, one of %(choices)s (default: %(default)s)")Metavars
A metavar is the placeholder name argparse shows for a value. By default an option uses its upper-cased dest, so --width displays as WIDTH. A positional argument uses its own name. An argument with choices shows the set instead, as in {debug,info}.
Use metavar when the default would be unclear or ugly:
parser.add_argument("--move", nargs=2, metavar=("SRC", "DST"),
help="move a file from SRC to DST")
parser.add_argument("--level", choices=["debug", "info"], metavar="LEVEL")With nargs=2, pass a tuple with one name per value. The first line produces --move SRC DST in the usage line. The second replaces {debug,info} with LEVEL. If you do that, put the valid values in the help string, because the metavar no longer shows them.
A metavar changes only the display. It does not change the attribute name on the result. That name still comes from dest.
Description, epilog and formatters
description appears between the usage line and the argument listing. epilog appears at the end. Use the description to say what the tool does. Use the epilog for examples, exit codes, or a pointer to documentation.
By default, argparse re-wraps both texts into one paragraph. A formatter class changes this behavior:
| Formatter class | Effect |
|---|---|
| `HelpFormatter` | The default. Re-wraps all text. |
| `RawDescriptionHelpFormatter` | Keeps line breaks in `description` and `epilog`. Still re-wraps `help=` strings. |
| `RawTextHelpFormatter` | Keeps line breaks in every text, including `help=` strings. |
| `ArgumentDefaultsHelpFormatter` | Appends `(default: ...)` to each help string. |
To combine two behaviors, subclass both, as the resize example does. Put the classes in the bases list and leave the body empty.
ArgumentDefaultsHelpFormatter appends the default only to arguments that have a help string. It skips arguments whose default is meaningless, such as a required positional or --version. It does add (default: False) to a store_true flag, which can look noisy. If that bothers you, write the default into the help strings yourself and use a plain formatter.
Hiding and reshaping usage
Pass help=argparse.SUPPRESS to leave an option out of the help listing. The option still works. Use this for debugging switches and deprecated options. Suppressed options are also left out of the usage line.
You can replace the generated usage line with usage="...", but doing so is rarely a good idea. A hand-written line goes stale when you add an option. Use it only when the generated line is too long to read, and then keep it in sync with the parser.
To print help from code, use these methods:
parser.print_help()writes the full help to stdout.parser.print_usage()writes only the usage line.parser.format_help()returns the full help as a string, which is useful for tests and documentation.
Help for subcommands
With add_subparsers, you write help in two places. The help= passed to add_parser is the one-line summary in the parent's command list. The description= is the longer text shown by todo add --help.
import argparse
parser = argparse.ArgumentParser(prog="todo")
sub = parser.add_subparsers(dest="command", required=True, metavar="COMMAND")
add = sub.add_parser("add", help="add an item",
description="Add an item to the list.")
add.add_argument("item", help="text of the new item")
parser.print_help()
add.print_help()The metavar="COMMAND" argument replaces the long {add,list} placeholder in the usage line. The command list then shows each command with its help= summary under a COMMAND heading.
Testing help output
Help text is part of your interface, so test it. Calling main(["--help"]) raises SystemExit, and capsys collects what was printed.
import pytest
from resize import main
def test_help_exits_zero_and_mentions_options(capsys):
with pytest.raises(SystemExit) as excinfo:
main(["--help"])
assert excinfo.value.code == 0
out = capsys.readouterr().out
assert "usage: resize" in out
assert "--width" in outThis test also catches the bare % problem, because rendering the help runs the placeholder expansion. Match on short, stable phrases. If you compare against a whole saved help message, the test breaks when the terminal width changes or when a Python release rewords a heading.
Common mistakes
- Writing
help=strings that start with a capital letter and end with a period in some options but not others. Pick one style and use it everywhere. - Using
RawTextHelpFormattereverywhere and then writing help lines wider than 80 columns. Raw formatters do not wrap for you. - Forgetting to mention units, such as seconds or pixels, or the accepted formats for a value.
- Setting a
metavarthat hideschoiceswithout listing the choices in the help string.
Exercise
A parser has parser.add_argument("--rate", type=float, default=0.5, help="sampling rate, default 50%"). The program runs normally, but --help crashes. What is the cause, how do you fix it, and how would you catch it in a test?
Show answer
Argparse treats % in a help string as the start of a format placeholder, so 50% is an invalid format and rendering the help fails. Write 50%%, or use %(default)s instead of typing the value. To catch it, add a test that calls main(["--help"]) inside pytest.raises(SystemExit), checks that the exit code is 0, and checks that the output contains the option name. The test fails with an error while the help is being rendered.