LESSON · 1 OF 5

argparse basics

argparse basics

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.

The parser

Start by creating an ArgumentParser. A short description shows up in the tool's help text:

python
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.

parse_args

Once the parser knows its arguments, parse_args reads them from the command line and returns an object holding the values:

python
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.

The shape of a tool

Almost every argparse tool follows the same three steps:

python
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.

What this node introduces

  • argparse.ArgumentParser(description=...) creates a parser.
  • parser.parse_args() reads and validates the command line.
  • The returned object holds the values your code then uses.
Spin up a fresh environment and practice live.
python-devops · fresh machine · ready in under a minute