Header Ads Widget

⚡ Premium Tools Hub • EXE Apps + Full Python Source Code
Lite • Pro • Bundle Packs • Instant Download

Python Command-Line Arguments Tutorial – sys.argv and argparse Explained

Python Command-Line Arguments

When running Python programs, we usually execute them like this:

python script.py

But 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 25

Here:

  • 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 25

Output

Script Name: script.py
Arguments: ['John', '25']

Understanding sys.argv

IndexMeaning
0Script name
1First argument
2Second argument

Example: Using Arguments

import sys

name = sys.argv[1]
age = sys.argv[2]

print(f"Name: {name}, Age: {age}")

Output

Name: John, Age: 25

2. 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 25

Output

John
25

4. 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 25

5. 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 --help

Output:

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 5

Output

Sum: 15
Difference: 5

9. 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.




Post a Comment

0 Comments