argparse.ArgumentParser() vs argparse.add_argument()
argparse.ArgumentParser() and argparse.add_argument() 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.ArgumentParser(): Creates an argument parser for processing command-line arguments. Its syntax is argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, formatter_class=argparse.HelpFormatter, add_help=True, allow_abbrev=True), and it returns argumentParser object 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 Example of argparse.ArgumentParser(): import argparse
parser = argparse.ArgumentParser(description="Process files")
parser.add_argument("input", help="input file")
parser.add_argument("--output", "-o", help="output file")
args = parser.parse_args()
print(args.input). Example of argparse.add_argument(): parser.add_argument("--verbose", "-v", action="store_true", help="increase output verbosity"). Read the full references for argparse.ArgumentParser() and argparse.add_argument() to see parameters, edge cases, and example code side by side. Other Argparse Module APIs worth comparing: argparse.parse_args(), argparse.Namespace. Both belong to the Argparse Module category in the Python Reference documentation.