How to Parse Command Line Arguments in Python with argparse

Build a CLI that accepts positional integers, an optional --sum flag, and a --verbose switch, all with Python's standard argparse library.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 12 views 0 copies

Python code

23 lines
Python 3.9+
import argparse

def main():
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('numbers', metavar='N', type=int, nargs='+',
                        help='an integer for the accumulator')
    parser.add_argument('--sum', dest='accumulate', action='store_const',
                        const=sum, default=max,
                        help='sum the integers (default: find the max)')
    parser.add_argument('--verbose', action='store_true',
                        help='increase output verbosity')

    args = parser.parse_args()

    if args.verbose:
        print(f"Numbers: {args.numbers}")
        print(f"Operation: {'sum' if args.accumulate is sum else 'max'}")

    result = args.accumulate(args.numbers)
    print(f"Result: {result}")

if __name__ == "__main__":
    main()

Output

stdout
$ python script.py 3 5 8
Result: 8

$ python script.py 3 5 8 --sum
Result: 16

$ python script.py 3 5 8 --sum --verbose
Numbers: [3, 5, 8]
Operation: sum
Result: 16

How it works

argparse is part of the standard library, so no pip install is needed. The add_argument method declares each expected input: positional numbers uses nargs='+' to accept one or more integers, --sum uses action='store_const' with const=sum to swap the default max function, and --verbose uses store_true for a boolean flag. After parse_args() returns the namespace args, the code checks args.verbose before printing extra details, then calls the selected function (max or sum) on the collected list of integers. This pattern of defining arguments and reading them into a namespace is the idiomatic way to build a small CLI in Python.

Common mistakes

  • Forgetting `nargs='+'` for positional arguments and getting a single value instead of a list
  • Using `action='store'` instead of `action='store_const'` for the --sum flag, which forces a value argument
  • Assuming `args.accumulate` is a boolean when it's actually a function reference (`sum` or `max`)

Variations

  1. Use `parser.add_argument('--sum', action='store_true')` and then branch on `args.sum` inside the code
  2. Add type checking with `type=float` and custom validation in a `parser.error()` call for non-integer input

Real-world use cases

  • A build automation script that accepts a directory path and optional --clean flag to purge output files before running.
  • A backend worker that takes one or more queue names as positional arguments and a --concurrency flag to scale processing.
  • A data export tool that ingests input filenames and a --format switch to toggle between CSV and JSON output.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.