Help text is your CLI's documentation; users read it before anything else.
argparse builds --help from what you declare, so a little effort pays off:
ArgumentParser(description=..., epilog=...): text before and after the argument list. Use the epilog for examples.help=on each argument: one short phrase.%(default)s,%(type)s,%(choices)sand%(prog)sare substituted.metavar=: the placeholder name in usage, such as--output FILEinstead of--output OUTPUT. A tuple names each value fornargs=N.help=argparse.SUPPRESShides an argument from help entirely.
Formatter classes change layout:
RawDescriptionHelpFormatterkeeps your line breaks in description and epilog (by default text is re-wrapped).RawTextHelpFormatterkeeps line breaks in argument help too.ArgumentDefaultsHelpFormatterappends "(default: ...)" automatically.MetavarTypeHelpFormatteruses type names as metavars.
You can combine two with multiple inheritance in a tiny subclass.
Since 3.13, add_argument(..., deprecated=True) and add_parser(..., deprecated=True) let you keep an old option working while printing a deprecation warning when it's used. In 3.13 the usage line no longer repeats the metavar for options with short and long forms (-o, --output FILE).
Example
import argparse
class Fmt(argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter):
pass
p = argparse.ArgumentParser(
prog="resize", formatter_class=Fmt, description="Resize images.",
epilog="examples:\n resize photo.jpg --width 800")
p.add_argument("image", help="input image")
p.add_argument("-w", "--width", type=int, default=1024, metavar="PX", help="target width")
p.add_argument("--quality", type=int, default=85, help=argparse.SUPPRESS)
p.add_argument("--old-flag", action="store_true", deprecated=True, help="use --width")
p.print_help()
p.parse_args(["x.jpg", "--old-flag"])
# usage: resize [-h] [-w PX] [--old-flag] image
# ...
# -w, --width PX target width (default: 1024)
# ...
# examples:
# resize photo.jpg --width 800
# resize: warning: option '--old-flag' is deprecated (stderr)Remember
- description, epilog and per-argument help build --help
- metavar names placeholders; SUPPRESS hides arguments
- Formatter classes control wrapping and default display; deprecated= is new in 3.13
Watch out for
- Writing multi-line examples in the epilog without RawDescriptionHelpFormatter; argparse re-wraps them into one paragraph.