← Back to Python Course | Chapter 12: Standard Library | Lesson 8 of 9

Python argparse Module

What is argparse?

argparse builds a command-line interface for your script declaratively: you describe what arguments the program accepts, and the module handles parsing sys.argv, validating input, and auto-generating a --help message from your descriptions -- all without you writing any manual string-splitting logic.

Example: What is argparse?

python
import argparse
parser = argparse.ArgumentParser()
print(parser)

Positional Arguments

Positional arguments are declared without a leading dash and are required by position -- omitting one causes argparse to print a usage error and exit before your program logic ever runs, which is useful for catching missing required input immediately.

Example: Positional Arguments

python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("name")
args = parser.parse_args(["Alex"])
print(args.name)

Optional Arguments

Optional arguments are declared with a leading -- (or a short -x alias) and are not required, letting the script run with sensible defaults if the user omits them. This is the natural fit for configuration flags that most users won't need to override.

Example: Optional Arguments

python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--greeting", default="Hello")
args = parser.parse_args([])
print(args.greeting)

Specifying Argument Types

By default every argument value argparse extracts is a plain string, even if it looks numeric on the command line. Passing type=int or type=float to add_argument() tells argparse to convert and validate the input automatically, raising a clear error if conversion fails.

Example: Specifying Argument Types

python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--age", type=int)
args = parser.parse_args(["--age", "25"])
print(args.age + 1)

Choices and Boolean Flags

choices=[...] restricts an argument to a fixed set of valid values, rejecting anything else with a helpful error message. action=store_true turns an argument into a simple on/off flag that needs no accompanying value, just its presence or absence on the command line.

Example: Choices and Boolean Flags

python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--mode", choices=["fast", "slow"])
parser.add_argument("--verbose", action="store_true")
args = parser.parse_args(["--mode", "fast", "--verbose"])
print(args.mode, args.verbose)

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.