Python Command-Line Arguments
When running Python programs, we usually execute them like this:
python script.pyBut sometimes we need to pass extra information while running the script.
This is done using Command-Line Arguments.
They allow users to pass input values directly when executing a program.
What are Command-Line Arguments?
Command-line arguments are values passed to a Python script from the terminal.
Example:
python app.py John 25Here:
- John → first argument
- 25 → second argument
Why Use Command-Line Arguments?
They help to:
- Pass input without modifying code
- Build CLI tools
- Automate tasks
- Create flexible programs
- Improve user interaction
1. Using sys.argv
Python provides the sys module to handle command-line arguments.
Example
import sys
print("Script Name:", sys.argv[0])
print("Arguments:", sys.argv[1:])Run Command
python script.py John 25Output
Script Name: script.py
Arguments: ['John', '25']Understanding sys.argv
| Index | Meaning |
|---|---|
| 0 | Script name |
| 1 | First argument |
| 2 | Second argument |
Example: Using Arguments
import sys
name = sys.argv[1]
age = sys.argv[2]
print(f"Name: {name}, Age: {age}")Output
Name: John, Age: 252. Handling Missing Arguments
import sys
if len(sys.argv) < 3:
print("Usage: python script.py name age")
else:
name = sys.argv[1]
age = sys.argv[2]
print(name, age)3. Using argparse Module (Recommended)
argparse is a powerful module for building CLI applications.
Basic Example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("name")
parser.add_argument("age")
args = parser.parse_args()
print(args.name)
print(args.age)Run Command
python script.py John 25Output
John
254. Optional Arguments
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--name")
parser.add_argument("--age")
args = parser.parse_args()
print(args.name)
print(args.age)Run Command
python script.py --name John --age 255. Default Values
parser.add_argument("--city", default="Unknown")6. Type Conversion
parser.add_argument("--age", type=int)Now input is automatically converted to integer.
7. Help Message
Run:
python script.py --helpOutput:
usage: script.py [-h] [--name NAME] [--age AGE]8. Building a Simple CLI Calculator
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("a", type=int)
parser.add_argument("b", type=int)
args = parser.parse_args()
print("Sum:", args.a + args.b)
print("Difference:", args.a - args.b)Run Command
python calc.py 10 5Output
Sum: 15
Difference: 59. sys.argv vs argparse
| Feature | sys.argv | argparse |
| Ease of use | Simple | Advanced |
| Validation | No | Yes |
| Help messages | No | Yes |
| Type handling | Manual | Automatic |
| Recommended | Small scripts | Large CLI apps |
10. Advanced Features of argparse
Store True/False Flags
parser.add_argument("--debug", action="store_true")Mutually Exclusive Arguments
group = parser.add_mutually_exclusive_group()
group.add_argument("--add", action="store_true")
group.add_argument("--remove", action="store_true")Real-World Applications
Command-line arguments are used in:
- Automation scripts
- DevOps tools
- Data processing scripts
- Machine learning training scripts
- API testing tools
- Backup utilities
Example: File Processor
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("filename")
args = parser.parse_args()
with open(args.filename, "r") as file:
print(file.read())Best Practices
- Use argparse for production scripts
- Validate input values
- Provide helpful descriptions
- Use default values where needed
- Keep CLI simple and user-friendly
Common Mistakes
Index Error in sys.argv
print(sys.argv[1])Fix:
Check length first.
Forgetting argparse setup
Always create ArgumentParser instance.
Summary
Python command-line arguments allow developers to pass input values when running scripts. The sys.argv module is simple, while argparse provides powerful features for building professional CLI applications.
Conclusion
Command-line arguments are essential for building flexible and automated Python tools. By mastering sys.argv and argparse, you can create powerful command-line applications for real-world use cases.


0 Comments