Using sys.argv
and argparse
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.")
sys.argv[0]
is always the script name.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.
argparse
Featurestype=int
, choices=[...]
parser.add_argument("--level", default=1)
action="store_true"
-h/--help
parser.add_mutually_exclusive_group()
argparse
for anything beyond trivial scripts.help
messages and sensible defaults.type=
or custom functions.-o
) and long (--output
) for usability.