Python Argparse

Python argparse General Use Guide argparse is Python’s standard library module for creating command-line interfaces. It’s a powerful tool for parsing command-line arguments and generating help messages. Basic Usage Pattern 1import argparse 2 3# 1. Create the parser 4parser = argparse.ArgumentParser(description='Description of your program') 5 6# 2. Add arguments 7parser.add_argument('--foo', help='foo help') 8parser.add_argument('bar', help='bar help') 9 10# 3. Parse the arguments 11args = parser.parse_args() 12 13# 4. Use the arguments 14print(args.foo) 15print(args.bar) Adding Arguments Positional Arguments 1parser.add_argument('filename', help='name of the file to process') Optional Arguments 1parser.add_argument('--verbose', '-v', help='increase output verbosity', action='store_true') Common Argument Types 1# String (default) 2parser.add_argument('--name', type=str, help='person name') 3 4# Integer 5parser.add_argument('--age', type=int, help='person age') 6 7# Float 8parser.add_argument('--price', type=float, help='item price') 9 10# Boolean flags 11parser.add_argument('--enable', action='store_true', help='enable feature') 12parser.add_argument('--disable', action='store_false', help='disable feature') 13 14# Choices 15parser.add_argument('--color', choices=['red', 'green', 'blue'], help='color choice') 16 17# Multiple values 18parser.add_argument('--numbers', nargs='+', type=int, help='list of numbers') Advanced Options 1# Required arguments 2parser.add_argument('--required-arg', required=True, help='this argument is required') 3 4# Default values 5parser.add_argument('--delay', type=int, default=10, help='delay in seconds') 6 7# Custom actions 8parser.add_argument('--version', action='version', version='%(prog)s 1.0') 9 10# Argument groups 11group = parser.add_argument_group('authentication') 12group.add_argument('--username', help='username') 13group.add_argument('--password', help='password') Parsing and Using Arguments 1args = parser.parse_args() 2 3# Access argument values 4if args.verbose: 5 print("Verbose mode enabled") 6 7if args.filename: 8 process_file(args.filename) Subcommands For complex CLI tools with multiple commands (like git): ...

May 12, 2025 · 3 min · 569 words · xxraincandyxx