ArgumentParser, add_argument, parse_args
class argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True, exit_on_error=True)
ArgumentParser.add_argument(name_or_flags, ..., type=None, default=None, choices=None, required=False, dest=None, help=None, nargs=None)
ArgumentParser.parse_args(args=None, namespace=None)Parse an explicit argument list into a Namespace, with type conversion, defaults, and choices.
| Parameter | Description |
|---|---|
prog | The program name used in usage text. Set it in examples so the output does not depend on the script path. |
name_or_flags | A positional dest, or one or more option strings such as -n and --count. |
type | A callable used to convert the argument string, such as int. |
args | The list to parse. None would mean sys.argv[1:]; do not omit it when you want a closed example. |
Returns: An argparse.Namespace whose attributes are the parsed values.
- The example never calls parse_args() without a list.
import argparse
parser = argparse.ArgumentParser(prog="demo", description="Demo parser")
parser.add_argument("path")
parser.add_argument("-n", "--count", type=int, default=1)
parser.add_argument("--mode", choices=("fast", "slow"), default="fast")
namespace = parser.parse_args(["notes.txt", "--count", "3"])
print(type(namespace).__name__)
print(namespace.path, namespace.count, namespace.mode)
print(vars(namespace))
Expected output
Namespace
notes.txt 3 fast
{'path': 'notes.txt', 'count': 3, 'mode': 'fast'}