Flags like --verbose and repeatable options like --include are in almost every CLI.
action= tells argparse what to do when it sees an option. The default, store, saves the following value. Others:
store_true/store_false: a flag with no value; sets True (or False). Default is the opposite.count: counts occurrences, so-vvvgives 3. Setdefault=0, otherwise the default isNone.append: repeatable option collecting values into a list:--include a --include bgives['a', 'b'].extend: like append but each occurrence can take several values (withnargs), flattened into one list.store_const/append_const: store a fixedconstvalue.version: printsversion=text and exits:add_argument("--version", action="version", version="%(prog)s 1.2").argparse.BooleanOptionalAction: creates a--color/--no-colorpair in one call.
One gotcha with append and a list default: the values are appended to the default list, so default=["x"] plus --include a gives ['x', 'a'], not ['a']. Use default=None and fill in the fallback after parsing.
Example
import argparse
p = argparse.ArgumentParser(prog="tool")
p.add_argument("-v", "--verbose", action="count", default=0)
p.add_argument("--dry-run", action="store_true")
p.add_argument("-I", "--include", action="append")
p.add_argument("--color", action=argparse.BooleanOptionalAction, default=True)
p.add_argument("--version", action="version", version="%(prog)s 1.2")
a = p.parse_args(["-vvv", "-I", "src", "--include", "lib", "--no-color"])
print(a.verbose, a.dry_run, a.include, a.color) # 3 False ['src', 'lib'] False
print(p.parse_args([]))
# Namespace(verbose=0, dry_run=False, include=None, color=True)
try:
p.parse_args(["--version"]) # tool 1.2
except SystemExit:
passRemember
- store_true for on/off flags, count for -vvv, append for repeatable options
- BooleanOptionalAction gives --x and --no-x
- action='version' prints and exits
Watch out for
- Giving an append option a non-empty list default; user values are added to it rather than replacing it.