How to Build Command-Line Interfaces with Argparse in Python
The Command Line Interface (CLI) allows users to interact with your Python programs using text commands, facilitating automation and scripting. While you can read raw arguments from sys.argv, Python's built-in argparse module provides a robust way to handle standard CLI behavior, such as help messages, type checking, and flexible argument parsing.
This guide explains how to build a user-friendly CLI tool using argparse.
Setting Up the Parser
The workflow for argparse always begins with importing the module and initializing the ArgumentParser object. This object holds all the information necessary to parse the command line into Python data types.
import argparse
# ✅ Correct: Initialize the parser with a description
parser = argparse.ArgumentParser(description="A simple command line interface.")
Defining Arguments: Positional vs. Optional
You need to tell the parser what arguments to expect. There are two main types:
- Positional Arguments: Mandatory. The order matters (unless specific logic changes it). No dashes (
-) are used in the definition. - Optional Arguments: Optional. They use flags (like
-nor--number). They can be in any order.
Adding a Positional Argument
# The user MUST provide this value
parser.add_argument("name", help="Your name")
Adding an Optional Argument
# The user MAY provide this. We can enforce types (e.g., int)
# 'default=1' ensures the code doesn't crash if the flag is omitted
parser.add_argument("-n", "--number",
help="Number of times to repeat the message",
type=int,
default=1)
If you define an argument with type=int, argparse automatically validates the input. If a user enters "abc" instead of a number, the program will exit with a helpful error message automatically.
Parsing and Accessing Values
After defining arguments, you call parse_args(). This inspects the command line, converts strings to the appropriate objects, and assigns them as attributes to a namespace.
args = parser.parse_args()
# Access values using the names defined in add_argument
print(f"Name provided: {args.name}")
print(f"Number provided: {args.number}")
Complete Code Example
Here is the complete script. Save this as my_program.py.
import argparse
# 1. Create the parser
parser = argparse.ArgumentParser(description="A greeter program.")
# 2. Add arguments
# Positional: 'name'
parser.add_argument("name", help="The name of the person to greet")
# Optional: '--number' or '-n'
parser.add_argument("-n", "--number",
help="Number of times to repeat the name",
type=int,
default=1) # Default prevents errors if flag is missing
# 3. Parse arguments
args = parser.parse_args()
# 4. Use the arguments
# We construct a string by repeating the name 'n' times
result = f"Hello, {args.name * args.number}"
print(result)
Execution Scenarios
Scenario 1: Standard Usage
python my_program.py John -n 3
Output:
Hello, JohnJohnJohn
Scenario 2: Using the Default (Omitting -n)
python my_program.py Alice
Output:
Hello, Alice
Scenario 3: requesting Help
argparse automatically generates a help page when you use -h.
python my_program.py -h
Output:
usage: my_program.py [-h] [-n NUMBER] name
A greeter program.
positional arguments:
name The name of the person to greet
optional arguments:
-h, --help show this help message and exit
-n NUMBER, --number NUMBER
Number of times to repeat the name
If you define a positional argument (like "name"), the user cannot use a flag (like --name) to invoke it. They must simply type the value. Conversely, optional arguments defined with flags (--number) require the flag to be typed before the value.
Conclusion
To create a Python CLI:
- Import
argparse. - Define
parser.add_argument("name")for mandatory inputs. - Define
parser.add_argument("--flag")for optional settings. - Parse with
args = parser.parse_args().
This structure ensures your program handles inputs gracefully and provides automatic help documentation for users.