Python:argparse
lastmod 2026-02-12created 2019-02-1112 edits
The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse figures out how to parse those arguments out of sys.argv. The argparse module also automatically generates help and usage messages. The module also issues errors when users give the program invalid arguments.
Giving default values to positional arguments
Use nargs='?' (or nargs='*' if you need more than one dir)
List (Append) arguments
parser = argparse.ArgumentParser()
parser.add_argument('--foo', action='append')
parser.parse_args('--foo 1 --foo 2'.split()) ## Namespace(foo=['1', '2'])
List (Extend) arguments
Stores a list and extends it with each argument value.
parser = argparse.ArgumentParser()
parser.add_argument("--foo", action="extend", nargs="+", type=str)
parser.parse_args(["--foo", "f1", "--foo", "f2", "f3", "f4"]) ## Namespace(foo=['f1', 'f2', 'f3', 'f4'])
Printing the version
The version= keyword argument is required in the add_argument() call. When invoked, it prints the version information and exits:
import argparse
parser = argparse.ArgumentParser(prog='PROG')
parser.add_argument('--version', action='version', version='%(prog)s 2.0')
parser.parse_args(['--version']) ## PROG 2.0
Mutually exclusive flags
parser = ArgumentParser(prog='PROG')
logging_group = parser.add_mutually_exclusive_group()
logging_group.add_argument("--colored-logging", action="store_true", default=False)
logging_group.add_argument("--simple-logging", action="store_true", default=False)
Using raw format for help output
Use RawDescriptionHelpFormatter:
parser = ArgumentParser(
prog='PROG',
description='...',
epilog='...',
formatter_class=RawDescriptionHelpFormatter,
)
Example
def _get_args_by_argparse(
cmdline: Optional[List[Any]] = None, namespace: Optional[Namespace] = None
) -> Namespace:
parser = ArgumentParser(description="Node client of RECC")
parser.add_argument(
"--version",
action="store_true",
help="Print the version number and exit.",
)
parser.add_argument(
"--timeout",
type=float,
metavar="seconds",
help="Response timeout seconds. (default: INF)",
)
parser.add_argument(
"--delay",
type=float,
default=DEFAULT_DELAY,
metavar="seconds",
help=f"Response delay seconds. (default: {DEFAULT_DELAY})",
)
parser.add_argument(
"address",
type=str,
nargs="?",
default=DEFAULT_NODE_ADDRESS,
help=f"Node address (default: {DEFAULT_NODE_ADDRESS})",
)
return parser.parse_args(
args=[str(x) for x in cmdline] if cmdline is not None else None,
namespace=namespace,
)
Troubleshooting
TypeError: can only concatenate str (not "int") to str
If you get the following error in ArgumentParser-related code,
pay attention to the types of the members assigned to the Namespace and the actions of the arguments added to the parser.
from argparse import ArgumentParser, Namespace
namespace = Namespace()
namespace.verbose = "0"
parser = ArgumentParser(description="MINIDUN")
parser.add_argument(
"--verbose",
"-v",
default=0,
action="count",
help="Be more verbose/talkative during the operation",
)
args = parser.parse_known_args(["-vv"], namespace)
If an argument has action="count" and a namespace argument is passed to #parse_args or #parse_known_args, it must be a countable type, i.e. int.
| WARNING |
| If the argument is a Count Action, counting continues from the value passed as the |
See also
- Python
- Python:configparser
- ConfigArgParse
- Gooey - turns command-line programs into GUI applications