Syntax
parser.add_argument("--count", type=int, default=1); parser.parse_args()Examples
Command-Line Arguments with argparse
Run as a Python 3.11+ script.
import argparse
parser = argparse.ArgumentParser(description="Repeat a greeting")
parser.add_argument("name")
parser.add_argument("--count", type=int, default=1)
args = parser.parse_args(["Ada", "--count", "2"])
for _ in range(args.count):
print(f"Hello, {args.name}")- Expected output: Hello, Ada Hello, Ada
- Passing a list makes the example deterministic. In an actual CLI, parse_args() with no argument reads the process command line.
Best practices
- Validate domain limits, such as nonnegative counts, after type conversion.
- Let argparse generate usage errors instead of indexing sys.argv manually.
Runtime & versions
Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Python language reference