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

Python argparse Module

argparse lets your program understand options typed after its name in the terminal, like a waiter taking a detailed order. It also makes helpful instructions automatically.
Syntax
python
import argparse

parser = argparse.ArgumentParser(description="text")
parser.add_argument("--option", help="text")
args = parser.parse_args()

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()  # builds a command-line interface declaratively
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")  # positional, required, no leading dash
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")  # optional, falls back to the default
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)  # converts the string input to int automatically
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"])  # restricted to these values
parser.add_argument("--verbose", action="store_true")  # on/off flag, no value needed
args = parser.parse_args(["--mode", "fast", "--verbose"])
print(args.mode, args.verbose)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Reading arguments with sys.argv and manual parsing, instead of letting argparse generate usage and error messages.
  2. Forgetting type=int, so numeric arguments arrive as strings and args.n + 1 fails.
  3. Naming an option without dashes, as in add_argument("name"), which makes it required positional rather than optional.

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.