Parse Command-Line Arguments with argparse
Core idea
ArgumentParser declares positional arguments and optional flags. parse_args converts supplied strings into a Namespace; type=int requests integer conversion. Passing an explicit list makes a parser test independent of the host command line.
import argparsep = argparse.ArgumentParser()p.add_argument("label")p.add_argument("--copies", type=int, default=1)a = p.parse_args(["box", "--copies", "3"])print(a.label, a.copies)The positional label is required and copies is converted to an integer.
Use a Boolean flag
import argparsep = argparse.ArgumentParser()p.add_argument("--preview", action="store_true")print(p.parse_args([]).preview)print(p.parse_args(["--preview"]).preview)The flag consumes no value and defaults to False.
Common mistake
Do not use type=bool to parse the text "false"; any nonempty string is truthy. Invalid arguments normally cause argparse to print a diagnostic and exit with status 2.
Practice
Add --copies with a positive-value check and test omitted, valid and invalid arguments in a local script.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Argument parsing
Check your understanding of argparse arguments.
What is printed?
import argparsep=argparse.ArgumentParser()p.add_argument("--n",type=int,default=5)print(p.parse_args([]).n)What is printed?
import argparsep=argparse.ArgumentParser()p.add_argument("name")print(p.parse_args(["rack"]).name)What is store_true for?
Why pass a fixed list to parse_args in tests?