TIL: Parsing Command-Line Arguments With Python's argparse
Python argparse module turns sys.argv into structured data. Built into the standard library, no deps.
import argparse
parser = argparse.ArgumentParser(description="Transcribe audio files")
parser.add_argument("file", help="path to audio file")
parser.add_argument("--model", default="nova-2", help="model name")
parser.add_argument("--verbose", action="store_true", help="show debug output")
args = parser.parse_args()
print(f"Transcribing {args.file} with {args.model}")
Running with –help generates the help text automatically.
parser.add_argument("--format", choices=["wav", "mp3", "flac"], default="wav")
Choices validation rejects invalid inputs with a clear error message.
Does argparse support subcommands?
Yes. Use parser.add_subparsers() for nested command structures.
Can I use environment variables as defaults?
Yes. Read the env var and pass it as the default parameter to add_argument.