Adding CLI Arguments
A script that only works one way isn't very useful. Real CLI tools accept arguments — you tell them what to do when you run them. Python's argparse module makes this straightforward, and AI can generate the boilerplate quickly.
What Arguments Enable
Without arguments, your script might be hardcoded to fetch Apple's stock price. With arguments, users can request any symbol:
Arguments make your tool flexible without changing code.
Argparse Basics
Here's a simple argument parser:
import argparse
parser = argparse.ArgumentParser(
description="Fetch current stock prices"
)
# Positional argument: required, can accept multiple values
parser.add_argument(
'symbols',
nargs='+', # One or more values
help='Stock ticker symbols (e.g., AAPL GOOGL)'
)
# Optional flag with choices
parser.add_argument(
'--format',
choices=['text', 'json', 'csv'],
default='text',
help='Output format (default: text)'
)
# Optional flag for file output
parser.add_argument(
'--output',
help='Save results to file'
)
args = parser.parse_args()
Now args.symbols contains a list of ticker symbols, args.format contains the chosen format, and args.output contains the filename (or None).
Built-in Help
Argparse automatically generates help text:
Users can discover how to use your tool without reading documentation.
Prompting AI for CLI Code
Ask AI to generate argument parsing that fits your needs:
Add command-line argument parsing to my stock fetcher using argparse:
- Accept one or more stock symbols as positional arguments
- Add --format flag with choices: 'text', 'json', 'csv'
- Add --output flag to save results to a file
- Include helpful --help documentation
Review the generated code to ensure it handles edge cases — what if someone provides no symbols? What if the output file can't be created?