Python Command-Line Arguments – Build Smart and User-Friendly CLI Tools
Introduction – Why Use Command-Line Arguments?
Command-line arguments allow your Python scripts to accept external input when they’re executed. This turns your script into a flexible, customizable tool without changing the code every time.
With command-line arguments, you can:
- Accept filenames, flags, and options
- Build testable and scriptable utilities
- Create professional-grade CLI tools
Python offers powerful libraries like sys.argv, argparse, and click to make this easy.
In this guide, you’ll learn:
- How to use
sys.argvandargparse - How to parse flags, arguments, and options
- Build real-world CLI tools
- Best practices and error handling
1. Using sys.argv – Quick and Basic
import sys
print("Script name:", sys.argv[0])
print("Arguments:", sys.argv[1:])
$ python script.py input.txt --verbose
Output:
Script name: script.py
Arguments: ['input.txt', '--verbose']
sys.argv is a list of strings, including the script name.
Limitations of sys.argv
- Manual parsing
- No type checking
- No built-in help messages
Use it for quick scripts, not for full-featured CLI apps.
2. Using argparse – Robust CLI Parsing
import argparse
parser = argparse.ArgumentParser(description="Example CLI")
parser.add_argument("filename", help="Input file name")
parser.add_argument("--verbose", action="store_true", help="Enable verbose mode")
args = parser.parse_args()
print("File:", args.filename)
print("Verbose:", args.verbose)
$ python script.py data.txt --verbose
Output:
File: data.txt
Verbose: True
argparse provides automatic help, validation, and error messages.
Add More Argument Types
parser.add_argument("--count", type=int, default=1, help="Number of repetitions")
Positional vs Optional Arguments
| Type | Syntax Example | Required? |
|---|---|---|
| Positional | filename | Yes |
| Optional | --verbose | No |
3. Advanced CLI with argparse
parser.add_argument("--mode", choices=["dev", "prod"], required=True)
$ python cli.py --mode dev
Combine Flags and Options
parser.add_argument("-n", "--number", type=int)
parser.add_argument("-v", "--verbose", action="store_true")
Real-World Example – CLI File Reader
# file_reader.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("file", help="File to read")
parser.add_argument("--lines", type=int, default=5, help="Lines to display")
args = parser.parse_args()
with open(args.file) as f:
for i in range(args.lines):
print(f.readline().strip())
$ python file_reader.py sample.txt --lines 3
Reads the first 3 lines of sample.txt.
Add Help and Usage Text
argparse.ArgumentParser(
prog="mytool",
description="Custom tool for automation",
epilog="Thanks for using!"
)
Run:
$ python tool.py --help
Auto-generates CLI help docs.
Best Practices
| Do This | Avoid This |
|---|---|
Use argparse for CLI tools | Parsing manually with sys.argv |
Add --help descriptions | Making flags without documentation |
Validate input with type and choices | Relying on string comparisons |
| Group related arguments | Mixing unrelated options in flat layout |
Summary – Recap & Next Steps
Python command-line arguments help you parameterize your scripts, making them flexible and user-friendly. argparse is the go-to tool for robust CLI interfaces.
Key Takeaways:
- Use
sys.argvfor simple input - Use
argparsefor professional CLI tools - Auto-generate help, validate types, add options
- Ideal for file readers, processors, automation tools, and system scripts
Real-World Relevance:
Used in dev tools, testing scripts, deployment pipelines, and data processing tasks.
FAQ – Python Command-Line Arguments
What is sys.argv in Python?
A list that contains command-line arguments passed to the script.
What’s the difference between sys.argv and argparse?
sys.argv is simple but manual.
argparse is a full-featured parser with validation and help.
How do I make a flag in argparse?
parser.add_argument("--debug", action="store_true")
Can I have multiple optional arguments?
Yes. Just add multiple add_argument() calls with -- prefix.
How do I access arguments inside the script?
After parsing:
args = parser.parse_args()
print(args.filename)
Share Now :
