Python Command-line Programs with argparse
What you will learn
- Why not parse
sys.argvby hand - Positional arguments, options, flags
- Types, defaults, choices, several values
- Subcommands
- Help and error messages for free
- A
main()function with exit codes, ready for testing
1. Programs controlled from the terminal
Many useful programs are run from a terminal with arguments: python tool.py data.txt --top 5. The raw arguments are in sys.argv (lesson 17.7), but parsing them by hand is tedious: options in any order, --top=5 versus --top 5, converting numbers, showing help, rejecting mistakes. The standard-library module argparse does all of that:
import argparse
You describe the arguments you expect; argparse reads sys.argv, converts and checks the values, and builds the --help text.
2. A first parser
parser = argparse.ArgumentParser(prog="greet", description="Greet someone.")
parser.add_argument("name")
parser.add_argument("-t", "--times", type=int, default=1, help="how many times")
parser.add_argument("--shout", action="store_true")
parser.add_argument("--lang", choices=["en", "bn"], default="en")
Calling parser.parse_args() with no argument reads the real command line. For learning, we pass a list instead, which works exactly the same:
print(parser.parse_args(["Rina"]))
args = parser.parse_args(["Rina", "-t", "3", "--shout", "--lang", "bn"])
print(args)
print(args.times, args.shout)
print(parser.parse_args(["Sam", "--times=2"]).times)
Namespace(name='Rina', times=1, shout=False, lang='en')
Namespace(name='Rina', times=3, shout=True, lang='bn')
3 True
2
parse_args returns a Namespace: an object with one attribute per argument (args.name, args.times). vars(args) turns it into a dictionary.
Kinds of argument
| Kind | Written as | Meaning |
|---|---|---|
| positional | add_argument("name") |
required, identified by position |
| option | add_argument("-t", "--times", ...) |
named, usually optional, takes a value |
| flag | add_argument("--shout", action="store_true") |
no value; True if present |
Useful keyword arguments of add_argument:
| Keyword | Effect |
|---|---|
type=int |
convert the text (also float, pathlib.Path, or your own function) |
default=... |
value when the option is absent |
choices=[...] |
only these values are allowed |
help="..." |
text for --help |
required=True |
make an option mandatory |
nargs="+" |
one or more values ("*" zero or more, "?" optional, a number for exactly that many) |
action="count" |
count repeats, as in -vv |
metavar="FILE" |
name shown in the help |
dest="name" |
attribute name in the namespace |
Quick check: how is `--shout` written when the user wants the flag on?
Just --shout, with no value. Without it, args.shout is False.
3. Errors and help come free
If the user makes a mistake, argparse prints a usage message to the error stream and exits with code 2:
parser.parse_args(["Rina", "-t", "x"])
parser.parse_args([])
parser.parse_args(["Rina", "--lang", "fr"])
parser.parse_args(["Rina", "--nope"])
usage: greet [-h] [-t TIMES] [--shout] [--lang {en,bn}] name
greet: error: argument -t/--times: invalid int value: 'x'
usage: greet [-h] [-t TIMES] [--shout] [--lang {en,bn}] name
greet: error: the following arguments are required: name
usage: greet [-h] [-t TIMES] [--shout] [--lang {en,bn}] name
greet: error: argument --lang: invalid choice: 'fr' (choose from en, bn)
usage: greet [-h] [-t TIMES] [--shout] [--lang {en,bn}] name
greet: error: unrecognized arguments: --nope
(Each call stops the program with code 2; in a test you can catch it as SystemExit.) The -h / --help option is added automatically:
parser.print_help()
usage: greet [-h] [-t TIMES] [--shout] [--lang {en,bn}] name
Greet someone.
positional arguments:
name
options:
-h, --help show this help message and exit
-t, --times TIMES how many times
--shout
--lang {en,bn}
The help text comes from your description and the help= strings, so writing good help strings is documentation for free.
4. More patterns
Several values with nargs, and counting repeats:
q = argparse.ArgumentParser()
q.add_argument("files", nargs="+")
q.add_argument("-v", "--verbose", action="count", default=0)
q.add_argument("--out", default=None)
q.add_argument("--n", type=float, nargs=2)
print(q.parse_args(["a.txt", "b.txt", "-vv"]))
print(q.parse_args(["x", "--n", "1.5", "2"]).n)
Namespace(files=['a.txt', 'b.txt'], verbose=2, out=None, n=None)
[1.5, 2.0]
Paths and on/off options:
import pathlib
s = argparse.ArgumentParser()
s.add_argument("path", type=pathlib.Path)
s.add_argument("--debug", action=argparse.BooleanOptionalAction, default=False)
print(s.parse_args(["x/y.txt", "--debug"]))
print(s.parse_args(["x", "--no-debug"]).debug)
Namespace(path=WindowsPath('x/y.txt'), debug=True)
False
BooleanOptionalAction creates both --debug and --no-debug. (WindowsPath appears on Windows; PosixPath elsewhere.)
Optional positional with nargs="?":
u = argparse.ArgumentParser()
u.add_argument("a", nargs="?", default="dflt")
print(u.parse_args([]).a, u.parse_args(["z"]).a)
dflt z
Subcommands, as in git commit and git push, give each action its own arguments:
r = argparse.ArgumentParser()
sub = r.add_subparsers(dest="cmd", required=True)
add = sub.add_parser("add")
add.add_argument("x", type=int)
add.add_argument("y", type=int)
neg = sub.add_parser("neg")
neg.add_argument("x", type=int)
print(r.parse_args(["add", "2", "3"]))
print(r.parse_args(["neg", "5"]))
Namespace(cmd='add', x=2, y=3)
Namespace(cmd='neg', x=5)
5. Structure of a good command-line program
Keep the logic in functions and make the top level thin:
parse_args(argv=None)builds the parser and returns the namespace.main(argv=None)does the work and returns an exit code (0for success, non-zero for failure).- The bottom of the file calls
sys.exit(main())under the main guard (lesson 16.2).
Passing argv as a parameter lets tests call main(["file.txt", "-n", "2"]) without touching the real command line. Print normal results to standard output, and error messages to standard error (print(..., file=sys.stderr)) so that they do not mix with the output when someone redirects it to a file.
Worked example: a word-frequency tool
wordfreq.py shows the most common words in a text file, with options for how many to show, a minimum word length, and case sensitivity. The text file story.txt contains three lines:
The cat and the dog.
The bird saw the cat!
A dog, a cat, a bird.
wordfreq.py:
import argparse
import re
import sys
from collections import Counter
from pathlib import Path
def parse_args(argv=None):
parser = argparse.ArgumentParser(
prog="wordfreq",
description="Show the most common words in a text file.")
parser.add_argument("path", type=Path, help="text file to read")
parser.add_argument("-n", "--top", type=int, default=3,
help="how many words to show (default: 3)")
parser.add_argument("-m", "--min-length", type=int, default=1,
help="ignore words shorter than this")
parser.add_argument("--keep-case", action="store_true",
help="treat The and the as different words")
return parser.parse_args(argv)
def main(argv=None):
args = parse_args(argv)
if not args.path.is_file():
print(f"wordfreq: no such file: {args.path}", file=sys.stderr)
return 1
text = args.path.read_text(encoding="utf-8")
if not args.keep_case:
text = text.lower()
words = [w for w in re.findall(r"[A-Za-z']+", text) if len(w) >= args.min_length]
for word, count in Counter(words).most_common(args.top):
print(f"{count:>3} {word}")
return 0
if __name__ == "__main__":
sys.exit(main())
Runs from a terminal (each was executed for this lesson):
$ python wordfreq.py story.txt
4 the
3 cat
3 a
$ python wordfreq.py story.txt -n 2 -m 3
4 the
3 cat
$ python wordfreq.py story.txt --keep-case -n 2
3 cat
2 The
$ python wordfreq.py nofile.txt
wordfreq: no such file: nofile.txt
(exit code 1)
$ python wordfreq.py story.txt -n many
usage: wordfreq [-h] [-n TOP] [-m MIN_LENGTH] [--keep-case] path
wordfreq: error: argument -n/--top: invalid int value: 'many'
(exit code 2)
and the generated help:
$ python wordfreq.py --help
usage: wordfreq [-h] [-n TOP] [-m MIN_LENGTH] [--keep-case] path
Show the most common words in a text file.
positional arguments:
path text file to read
options:
-h, --help show this help message and exit
-n, --top TOP how many words to show (default: 3)
-m, --min-length MIN_LENGTH
ignore words shorter than this
--keep-case treat The and the as different words
| Part | Idea |
|---|---|
type=Path, type=int |
the values arrive converted; bad numbers are rejected by argparse |
--min-length becomes args.min_length |
dashes turn into underscores |
return 1 for a missing file |
our own error, with the message on standard error |
sys.exit(main()) |
the exit code reaches the terminal |
main(["story.txt", "-n", "2"]) |
how a test would call it, with no real command line |
The sentences are made up. In the first run cat and a tie at 3, and Counter.most_common lists tied words in the order they first appeared (lesson 17.3); with -m 3 the one-letter word a is dropped.
Common mistakes
- Parsing
sys.argvby hand whenargparsedoes it better. - Forgetting
type=int, so numbers stay as strings. - Printing errors to standard output instead of standard error.
- Putting all the code at the top level, which makes testing impossible; use
main(argv=None). - Ignoring exit codes: return non-zero when something fails.
- Expecting dashes in names (
args.min-length); it isargs.min_length. - Calling
parse_args()at import time of a module.
Key takeaways
argparse.ArgumentParserplusadd_argumentdescribe the command line;parse_argsreturns aNamespace.- Positional arguments are required; options start with
-or--; flags useaction="store_true". type,default,choices,nargsandhelpcontrol values; usage errors and--helpare automatic (exit code 2 for errors).- Subparsers give commands with their own arguments.
- Write
main(argv=None)that returns an exit code, call it withsys.exit(main()), and test it by passing a list.
Practice
1. Add an option --count taking an integer, default 5.
Show answer
parser.add_argument("--count", type=int, default=5)
2. How does a flag differ from an option?
Show answer
A flag (action="store_true") takes no value and is just on or off; an option takes a value after it.
3. What exit code does argparse use for a usage error?
Show answer
2.
4. How do you accept one or more file names?
Show answer
parser.add_argument("files", nargs="+")
5. Why give main an argv parameter?
Show answer
So tests (or other code) can pass a list of arguments directly instead of relying on the real command line.
6. Where should error messages be printed, and why?
Show answer
To standard error (file=sys.stderr), so they stay visible and do not get mixed into redirected normal output.