Python: Argparse Command-Line Parsing
Table of Contents
Section titled “Table of Contents”- Basic Argparse Usage
- Common Argument Types
- Subcommands Example
- Mutually Exclusive Arguments
- Custom Validation
Basic Argparse Usage
Section titled “Basic Argparse Usage”#!/usr/bin/env pythonimport argparseimport logging
logging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
def parse_args(): parser = argparse.ArgumentParser( description="Example script demonstrating argparse features" )
# Required argument with custom destination parser.add_argument( "--arg", dest="arg_weird_dest", required=True, help="A required argument with custom destination name" )
# Boolean flag (defaults to False) parser.add_argument( "--flg", action="store_true", help="Enable a feature (flag is False by default)" )
return parser.parse_args()
if __name__ == "__main__": args = parse_args() logger.info(f"Argument value: {args.arg_weird_dest}") logger.info(f"Flag enabled: {args.flg}")Common Argument Types
Section titled “Common Argument Types”import argparse
parser = argparse.ArgumentParser()
# Positional argument (required by default)parser.add_argument("input_file", help="Path to input file")
# Optional argument with default valueparser.add_argument("--output", default="output.txt", help="Output file path")
# Integer argumentparser.add_argument("--count", type=int, default=10, help="Number of iterations")
# Float argumentparser.add_argument("--threshold", type=float, default=0.5, help="Threshold value")
# Multiple valuesparser.add_argument("--files", nargs="+", help="One or more file paths")
# Choice from a listparser.add_argument( "--format", choices=["json", "yaml", "xml"], default="json", help="Output format")
# Store constant valueparser.add_argument( "--verbose", "-v", action="store_const", const=logging.DEBUG, default=logging.INFO, help="Enable verbose logging")
args = parser.parse_args()Subcommands Example
Section titled “Subcommands Example”import argparse
def cmd_create(args): print(f"Creating resource: {args.name}") if args.force: print("Force mode enabled")
def cmd_delete(args): print(f"Deleting resource: {args.name}") if args.confirm: print("Confirmed deletion")
parser = argparse.ArgumentParser(description="Resource management CLI")subparsers = parser.add_subparsers(dest="command", help="Available commands")
# Create subcommandcreate_parser = subparsers.add_parser("create", help="Create a new resource")create_parser.add_argument("name", help="Resource name")create_parser.add_argument("--force", action="store_true", help="Force creation")create_parser.set_defaults(func=cmd_create)
# Delete subcommanddelete_parser = subparsers.add_parser("delete", help="Delete a resource")delete_parser.add_argument("name", help="Resource name")delete_parser.add_argument("--confirm", action="store_true", help="Confirm deletion")delete_parser.set_defaults(func=cmd_delete)
args = parser.parse_args()if hasattr(args, "func"): args.func(args)else: parser.print_help()Mutually Exclusive Arguments
Section titled “Mutually Exclusive Arguments”import argparse
parser = argparse.ArgumentParser()
# Only one of these can be specifiedgroup = parser.add_mutually_exclusive_group(required=True)group.add_argument("--read", action="store_true", help="Read mode")group.add_argument("--write", action="store_true", help="Write mode")group.add_argument("--delete", action="store_true", help="Delete mode")
args = parser.parse_args()Custom Validation
Section titled “Custom Validation”import argparseimport os
def valid_file(path): """Custom validator for file paths""" if not os.path.isfile(path): raise argparse.ArgumentTypeError(f"{path} is not a valid file") return path
def valid_port(value): """Custom validator for port numbers""" ivalue = int(value) if ivalue < 1 or ivalue > 65535: raise argparse.ArgumentTypeError(f"{value} is not a valid port (1-65535)") return ivalue
parser = argparse.ArgumentParser()parser.add_argument("--config", type=valid_file, help="Configuration file path")parser.add_argument("--port", type=valid_port, default=8080, help="Server port")
args = parser.parse_args()