A script that needs input can read sys.argv by hand, but then you're
writing your own code to check how many arguments came in, print usage
when they're wrong, and convert strings to numbers. The argparse
module in the standard library does all of that for you and gives your
script the same feel as ls or git.
Start by creating an ArgumentParser. A short description shows up in
the tool's help text:
import argparse
parser = argparse.ArgumentParser(description="Scale a service")
This object collects the arguments your tool accepts. You describe each one, then ask it to read what the user actually typed.
Once the parser knows its arguments, parse_args reads them from the
command line and returns an object holding the values:
args = parser.parse_args()
parse_args looks at what came in on the command line, checks it
against the arguments you defined, and stops the program with a helpful
message if something is missing or wrong. When it returns, you have
clean, validated values to work with.
Almost every argparse tool follows the same three steps:
import argparse
parser = argparse.ArgumentParser(description="Scale a service")
# (arguments get added here)
args = parser.parse_args()
# (your logic uses args here)
The next nodes fill in the middle: how to add arguments the user must supply, optional flags, and how to control their help text and types.
argparse.ArgumentParser(description=...) creates a parser.parser.parse_args() reads and validates the command line.