Command-Line Arguments and Building CLI Tools
Turn a script into a real tool that reads options from the command line with argparse
argparse takes that raw list of words, checks it against the arguments you declared, converts each value to the right type, generates a help screen for free, and hands you a tidy object with your settings. You describe what the tool accepts; argparse does the parsing, validating and error-reporting for you.
- read raw arguments from
sys.argvand see why it is not enough, - declare positional arguments and optional flags with
add_argument, - set
defaultvalues, convert withtype, and restrict withchoices, - add on/off switches with
action="store_true", - write good
helptext and read the auto-generated usage screen, - split a big tool into subcommands like
addandlist.
1. The raw material: sys.argv
When you run python greet.py Alice --loud, Python hands your program the words that followed it as a list of strings called sys.argv. The first item is always the script name; the rest are what the user typed.
import sys
# run as: python greet.py Alice --loud
print(sys.argv)
# ['greet.py', 'Alice', '--loud']
You could parse that list by hand, but you would quickly be writing fragile code: checking lengths, hunting for --loud, converting "3" to an int, printing a help message, and reporting friendly errors when the user mistypes. Every serious tool needs the same plumbing, so the standard library ships it as argparse.
Notice that everything in sys.argv is a string, even "3". Converting and validating those strings is exactly the work argparse takes off your hands.