Skip to main content Brad's PyNotes

Argparse Module: Professional Command-Line Argument Parsing

TL;DR

The argparse module provides powerful command-line argument parsing with automatic help generation, type checking, subcommands, and error handling for building professional CLI applications.

Interesting!

Argparse automatically generates help messages and usage information, and it can parse complex argument combinations including positional args, optional flags, subcommands, and even mutually exclusive groups - all with built-in validation.

Basic Argument Parsing

python code snippet start

import argparse

parser = argparse.ArgumentParser(description='Process some files.')

# Positional argument
parser.add_argument('filename', help='Input file to process')

# Optional arguments
parser.add_argument('-o', '--output', help='Output file')
parser.add_argument('-v', '--verbose', action='store_true', 
                   help='Enable verbose output')
parser.add_argument('--count', type=int, default=1,
                   help='Number of times to process')

args = parser.parse_args()
print(f"Processing: {args.filename}")
if args.verbose:
    print("Verbose mode enabled")

python code snippet end

Subcommands for Complex Applications

python code snippet start

parser = argparse.ArgumentParser(description='Git-like CLI tool')
subparsers = parser.add_subparsers(dest='command', help='Available commands')

# Create subcommand
create_parser = subparsers.add_parser('create', help='Create a new project')
create_parser.add_argument('name', help='Project name')
create_parser.add_argument('--template', choices=['basic', 'advanced'],
                          default='basic', help='Project template')

# List subcommand
list_parser = subparsers.add_parser('list', help='List projects')
list_parser.add_argument('--format', choices=['table', 'json'],
                        default='table', help='Output format')

args = parser.parse_args()

if args.command == 'create':
    print(f"Creating project '{args.name}' with template '{args.template}'")
elif args.command == 'list':
    print(f"Listing projects in {args.format} format")

python code snippet end

Argument Groups and Validation

python code snippet start

parser = argparse.ArgumentParser()

# Mutually exclusive arguments
format_group = parser.add_mutually_exclusive_group()
format_group.add_argument('--json', action='store_true', help='JSON output')
format_group.add_argument('--xml', action='store_true', help='XML output')

# Custom validation
def valid_port(string):
    value = int(string)
    if not 1 <= value <= 65535:
        raise argparse.ArgumentTypeError(f"Port must be 1-65535, got {value}")
    return value

parser.add_argument('--port', type=valid_port, help='Port number')

python code snippet end

The argparse module transforms simple scripts into professional command-line tools with robust argument handling and excellent user experience. It works seamlessly with sys.argv access and integrates with subprocess execution for building complete automation tools. For input validation, combine argparse with pathlib for file validation and robust error handling . For CLI help formatting, leverage text wrapping capabilities and integrate with virtual environments for distributable CLI applications.

Reference: Python Argparse Module Documentation