Python Command‑Line Arguments

Using sys.argv and argparse

1. Why Use Command‑Line Arguments?

2. Quick & Easy: sys.argv

sys.argv is a list containing the script name and any arguments.

import sys

# python greet.py John 55
script, name, age = sys.argv
print(f"Hello, {name}! You are {age} years old.")

3. Robust Parsing: argparse

The argparse module provides automatic help messages, type conversion, default values, and more.

import argparse

parser = argparse.ArgumentParser(description="Greet a user.")
parser.add_argument("name", help="Name of the user")
parser.add_argument("age", type=int, help="Age of the user")
parser.add_argument("-v", "--verbose", action="store_true",
                    help="Enable verbose output")

args = parser.parse_args()

greeting = f"Hello, {args.name}! You are {args.age}."
if args.verbose:
    greeting += " Nice to meet you!"

print(greeting)

Run python greet.py John 55 --verbose to see the optional flag in action.

4. Common argparse Features

5. Best Practices