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
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
parser.add_argument("name", help="Your name")Adding an Optional Argument
parser.add_argument("-n", "--number",
help="Number of times to repeat the message",
type=int,
default=1)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()
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
parser = argparse.ArgumentParser(description="A greeter program.")
parser.add_argument("name", help="The name of the person to greet")
parser.add_argument("-n", "--number",
help="Number of times to repeat the name",
type=int,
default=1) # Default prevents errors if flag is missing
args = parser.parse_args()
result = f"Hello, {args.name * args.number}"
print(result)Execution Scenarios
Scenario 1: Standard Usage
python my_program.py John -n 3Output:
Hello, JohnJohnJohnScenario 2: Using the Default (Omitting -n)
python my_program.py AliceOutput:
Hello, AliceScenario 3: requesting Help
argparse automatically generates a help page when you use -h.
python my_program.py -hOutput:
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 nameConclusion
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.