π» 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.argv
andargparse
- 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.argv
for simple input - β
Use
argparse
for 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 :