Skip to content
shellhacks.dev
Python

Parse Command-Line Options in Python with argparse

Build a command line in Python with argparse: one positional argument, a typed option and a flag. It writes the usage text and exits with status 2 on bad input.

2 min read
Summarize in AI

A script needs a name, a repeat count and a switch, with help text and error messages that you would rather not write by hand.

Shell
cat > greet.py <<'EOF'
import argparse

p = argparse.ArgumentParser(description="Greet someone")
p.add_argument("name")
p.add_argument("-n", "--times", type=int, default=1, help="repeat count")
p.add_argument("--shout", action="store_true")
a = p.parse_args()
for _ in range(a.times):
    print(a.name.upper() if a.shout else a.name)
EOF
python3 greet.py ann -n 2 --shout
python3 greet.py --help
python3 greet.py ann -n two
echo "exit status: $?"
Text
ANN
ANN
usage: greet.py [-h] [-n TIMES] [--shout] name

Greet someone

positional arguments:
  name

options:
  -h, --help            show this help message and exit
  -n TIMES, --times TIMES
                        repeat count
  --shout
usage: greet.py [-h] [-n TIMES] [--shout] name
greet.py: error: argument -n/--times: invalid int value: 'two'
exit status: 2

ArgumentParser collects the definitions, and parse_args() reads sys.argv and returns an object with one attribute per argument. type=int converts the value or stops with an error, action="store_true" makes a flag, and -h is added for free, using the description and help strings. In the run, a bad count printed the usage and invalid int value: 'two', and the exit status was 2. See argparse.

The heading in the help output reads options: in Python 3.10 and later and optional arguments: before. For many subcommands, use add_subparsers. For tools where startup time matters, argparse is a measurable import, but fine for ordinary scripts.

Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.