argparse.add_argument() vs argparse.parse_args()
argparse.add_argument() and argparse.parse_args() are both Python Argparse Module APIs, and choosing between them is a common point of confusion. This page compares their syntax, parameters, return values, and typical use cases so you can pick the right one. argparse.add_argument(): Defines a command-line argument the parser should accept. Its syntax is argparse.add_argument(*name_or_flags, action=None, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, dest=None), and it returns action object argparse.parse_args(): Parses the command-line arguments and returns a Namespace object. Its syntax is argparse.parse_args(args=None, namespace=None), and it returns namespace object Example of argparse.add_argument(): parser.add_argument("--verbose", "-v", action="store_true", help="increase output verbosity"). Example of argparse.parse_args(): args = parser.parse_args(["--output", "out.txt", "in.txt"])
args.output # "out.txt"
args.input # "in.txt". Read the full references for argparse.add_argument() and argparse.parse_args() to see parameters, edge cases, and example code side by side. Other Argparse Module APIs worth comparing: argparse.ArgumentParser(), argparse.Namespace. Both belong to the Argparse Module category in the Python Reference documentation.