How to parse command-line arguments with argparse

· Category: Python Programming

Short answer

argparse is Python's standard library module for parsing command-line arguments. It automatically generates help messages, validates types, and supports complex hierarchies with subparsers.

Details

A basic CLI can be built in a few lines:

import argparse
parser = argparse.ArgumentParser(description="Process some files.")
parser.add_argument("input", help="input file path")
parser.add_argument("--verbose", action="store_true", help="enable verbose output")
args = parser.parse_args()

For larger tools, group related arguments and use subparsers to mimic Git-style commands. Robust scripts should validate file existence and handle bad inputs with Python error handling. If your tool reads configuration, combine argparse with Python file I/O to merge CLI flags with JSON or INI settings. Logging verbosity flags work well alongside a proper Python logging setup for production-grade diagnostics.

Tips

  • Use type= with custom functions to validate inputs beyond built-in types.
  • Set default=argparse.SUPPRESS to distinguish between missing flags and explicit defaults.
  • Add metavar descriptions to keep generated help text clean and user-friendly.