Command-line arguments with argparse
- Version
- 3.14
- Since
- 3.2
- Review
- Draft
Summary#
argparse declares positional arguments and options, converts their values and generates help text. parse_args stores parsed values in a namespace under their destination names.
Syntax#
parser = argparse.ArgumentParser(exit_on_error=False)
parser.add_argument("source")
parser.add_argument("-n", "--limit", type=int, default=10)
parser.add_argument("--verbose", action="store_true")
parser.add_argument("--color", action=argparse.BooleanOptionalAction, default=True)
args = parser.parse_args()
Example#
import argparse
parser = argparse.ArgumentParser(prog="report", exit_on_error=False)
parser.add_argument("source")
parser.add_argument("-n", "--limit", type=int, default=10)
parser.add_argument("--verbose", action="store_true")
parser.add_argument("--color", action=argparse.BooleanOptionalAction, default=True)
args = parser.parse_args(["data.csv", "-n", "3", "--no-color"])
print(args.source, args.limit, args.verbose, args.color)
try:
parser.parse_args(["data.csv", "--limit", "many"])
except argparse.ArgumentError as error:
print("invalid limit:", type(error).__name__)
Expected output#
data.csv 3 False False
invalid limit: ArgumentError
Common mistakes#
type=bool turns every non-empty string into True, including "False". Use action="store_true" for a switch or argparse.BooleanOptionalAction for paired positive and negative flags. By default an invalid argument prints an error and exits with status 2. exit_on_error=False lets the example catch the conversion error, while built-in --help still prints help and exits with status 0.
Version applicability#
argparse was added in Python 3.2. BooleanOptionalAction and the exit_on_error parameter both require Python 3.9 or later, so both snippets start at 3.9.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0