argparse

Command-line argument parser included in Python's standard library. Provides basic CLI functionality without requiring additional dependencies.

pythonclistandard-libraryparser

Framework

argparse

Overview

argparse is a command-line argument parser included in Python's standard library. It provides basic CLI functionality without requiring additional dependencies. It includes features necessary for building robust CLI applications such as type conversion, validation, automatic help generation, and subcommand support.

Details

argparse was added to the standard library in Python 2.7 and 3.2, replacing the earlier optparse module. As part of the standard library, it's available without additional installation and is an ideal choice when you want to minimize dependencies. It's used in many Python scripts and applications, making it a proven solution.

Key Features

  • Standard Library: No additional installation required
  • Automatic Help Generation: Automatically generates help messages with -h, --help
  • Type Conversion and Validation: Type specification and automatic conversion for arguments
  • Positional and Optional Arguments: Supports both types
  • Subcommands: Enables creation of complex CLI structures
  • Mutually Exclusive Groups: Define mutually exclusive arguments
  • Custom Actions: Implementation of custom argument processing logic

Pros and Cons

Pros

  • Zero Dependencies: No additional installation required as it's part of the standard library
  • Stability: Proven library used for many years
  • Comprehensive Features: Provides all necessary features for basic CLI applications
  • Learning Cost: Abundant learning resources as part of Python's standard library
  • Portability: Works anywhere Python standard environment is available

Cons

  • Verbose Syntax: Code can be more verbose compared to advanced libraries
  • Limited Customization: Not as flexible as external libraries
  • Subcommand Complexity: Complex subcommand structures can become cumbersome to write
  • Error Messages: Default error messages may not always be user-friendly

Key Links

Example Usage

import argparse

# Create basic argument parser
parser = argparse.ArgumentParser(description='File processing tool')

# Positional arguments
parser.add_argument('filename', help='Name of file to process')

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

# Limit choices
parser.add_argument('--format', choices=['json', 'xml', 'yaml'], 
                    default='json', help='Output format')

# Accept multiple values
parser.add_argument('--tags', nargs='+', 
                    help='Specify one or more tags')

# Subcommands example
subparsers = parser.add_subparsers(dest='command', help='Available commands')

# 'process' subcommand
process_parser = subparsers.add_parser('process', help='Process file')
process_parser.add_argument('--mode', choices=['fast', 'thorough'], 
                           default='fast', help='Processing mode')

# 'validate' subcommand
validate_parser = subparsers.add_parser('validate', help='Validate file')
validate_parser.add_argument('--strict', action='store_true', 
                            help='Execute strict validation')

# Parse arguments
args = parser.parse_args()

# Use arguments
if args.verbose:
    print(f"Processing: {args.filename}")
    print(f"Output: {args.output}")
    print(f"Format: {args.format}")

if args.command == 'process':
    print(f"Processing mode: {args.mode}")
elif args.command == 'validate':
    if args.strict:
        print("Executing strict validation...")