๐ฅ๏ธ Python argparse โ Building Command-Line Tools
argparse turns Python scripts into professional CLI tools with automatic help messages, type validation, and optional/required arguments.
Use sys.argv for very simple scripts; switch to argparse as soon as you have more than 2 arguments.
๐ป Code Example:
import argparse # 1. Create parser parser = argparse.ArgumentParser( prog='pynfinity-tool', description='Pynfinity CLI โ Python learning toolkit by santoshtvk' ) # 2. Add arguments parser.add_argument('topic', type=str, help='Topic to search (e.g., regex)') parser.add_argument('--limit', type=int, default=5, help='Number of results to show (default: 5)') parser.add_argument('--format', choices=['json', 'table', 'plain'], default='table', help='Output format') parser.add_argument('--verbose', '-v', action='store_true', help='Enable verbose output') parser.add_argument('--output', '-o', type=str, metavar='FILE', help='Save results to file') # 3. Parse arguments args = parser.parse_args() # 4. Use the arguments print(f"Searching Pynfinity for: {args.topic}") print(f"Limit: {args.limit} | Format: {args.format}") if args.verbose: print("[DEBUG] Verbose mode enabled") if args.output: print(f"Results will be saved to: {args.output}") # Usage examples: # python tool.py regex --limit 10 --format json # python tool.py decorators -v -o results.txt # python tool.py --help # Auto-generated help!
| Concept | Key Takeaway |
|---|---|
| Positional arg | Required โ just type the name |
| --optional arg | Optional flag โ provides a default |
| action='store_true' | Boolean flag (--verbose) |
| choices=[...] | Restrict to allowed values |
| metavar='NAME' | Display name in help text |
Keep exploring and happy coding! ๐