Python Command Line Arguments: The Basics
Working with command line arguments is a fundamental skill for building flexible and user-friendly Python scripts. Instead of hardcoding values, developers can pass parameters directly when running a program. Python's built-in argparse module, part of the standard library, provides powerful tools for handling arguments efficiently.
Why Use Command Line Arguments?
Using command line arguments in Python offers several key benefits:
- Increased flexibility — change program behavior without modifying source code
- Easier automation and scripting for repetitive tasks
- Simplified integration into pipelines and CI/CD workflows
- Faster testing with different parameters
- Professional CLI tool development
Real-World Examples of CLI Tools
Many popular tools rely on command line arguments:
- Package managers (pip, apt, yarn)
- File utilities (tar, zip, rsync)
- Build systems (make, cmake, gradle)
- DevOps tools (git, docker, kubectl)
- Custom automation scripts
Importing and Setting Up argparse
The argparse module is included in Python's standard library from versions 2.7 and 3.2 onward. No extra installation is needed.
import argparse
Creating a Basic Parser
Start by creating an instance of the ArgumentParser class:
parser = argparse.ArgumentParser(description="Program description")
Your First argparse Example
Here's a simple script that takes a username and prints a personalized greeting:
import argparse
parser = argparse.ArgumentParser(description="Simple greeting program")
parser.add_argument("name", help="User's name")
args = parser.parse_args()
print(f"Hello, {args.name}!")
Run the script like this:
python script.py John
Output:
Hello, John!
Argument Types in argparse
Positional (Required) Arguments
Positional arguments are mandatory parameters that must be provided when running the script. They are defined without any prefix.
parser.add_argument("filename", help="File to process")
parser.add_argument("output_dir", help="Directory to save results")
Optional Arguments
Optional arguments start with a single dash (-) for short form or double dash (--) for long form. They add extra functionality.
parser.add_argument("-v", "--verbose", help="Show detailed output", action="store_true")
parser.add_argument("-o", "--output", help="Output file path")
Working with Data Types
By default, all arguments are treated as strings. Use the type parameter to specify a different data type:
parser.add_argument("number", type=int, help="Enter an integer")
parser.add_argument("price", type=float, help="Product price")
parser.add_argument("enabled", type=bool, help="Enable feature")
When passing n