Hi Pythonistas!
When writing Python scripts, we often want to pass arguments from the command line. While sys.argv is the simplest way, it's not the best tool for the job.
using sys.argv
import sys
name = sys.argv[1]
print(f"Hello, {name}!")
Problems:
- No built-in help messages.
- Manual index management.
- No default values.
- No type validation.
- Hard to handle optional vs positional args.
The Better Way — argparse
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--name', default='Guest')
args = parser.parse_args()
print(f"Hello, {args.name}!")
Now you can run:
python script.py --name Harry
Or just:
python script.py
And it defaults to:
Hello, Guest!
Positional vs Optional Arguments
argparse supports both positional and optional arguments
Positional Argument - Defined without dashes
parser.add_argument('filename') # required positional argument
Run with:
python script.py file.txt
If you don’t supply it, argparse throws an error.
Optional Argument - Defined with dashes
parser.add_argument('--name', default='Guest')
Run with:
python script.py --name Harry
If omitted, it uses the default value (Guest).
Bonus: Built-in Help
python script.py --help
You get this for free:
usage: script.py [-h] [--name NAME]
optional arguments:
-h, --help show this help message and exit
--name NAME your name (default: Guest)
Why Prefer argparse?
- Cleaner code
- Auto-generated help
- Input validation
- Default values
- Explicit positional vs optional control
please share your valuable suggestions with afsal@parseltongue.co.in