Python Basics: Adding Command-Line Arguments with argparse
Python’s standard-library argparse module turns command-line arguments into named values. It also generates help text and reports invalid input.
Use Python 3 on Linux. Run the shell commands in the same shell. Start in a fresh temporary directory so creating the example script cannot overwrite your work:
cd "$(mktemp -d)"Create a small command
Save as greet.py:
import argparse
parser = argparse.ArgumentParser(description="Print a short greeting.")
parser.add_argument("name", help="person to greet")
parser.add_argument("--count", type=int, choices=range(1, 4), default=1,
help="number of greetings (1 to 3)")
parser.add_argument("--upper", action="store_true", help="use uppercase")
args = parser.parse_args()
message = f"Hello, {args.name}!"
if args.upper:
message = message.upper()
for _ in range(args.count):
print(message)Run:
python3 greet.py AdaOutput:
Hello, Ada!name is a required positional argument. --count is an optional integer with a default of one. --upper is a flag: absent means False, present means True.
Pass options and a name with spaces
python3 greet.py "Ada Lovelace" --count 2 --upperOutput:
HELLO, ADA LOVELACE!
HELLO, ADA LOVELACE!Shell quotes keep the two-word name together as one argument. They are removed by the shell before Python receives the value.
To pass a positional value beginning with a dash, put it after --:
python3 greet.py -- -guestOutput:
Hello, -guest!Inspect help and invalid input
python3 greet.py --helpThe generated help lists name, --count, --upper, and -h/--help. Its layout can vary by Python version.
Try a count outside the allowed range. This command is expected to fail; run the following printf immediately afterward to inspect its exit status:
python3 greet.py Ada --count 0
printf 'exit=%s\n' "$?"Python prints usage and an invalid-choice message to standard error. The final line on standard output is:
exit=2type=int checks conversion, while choices limits the accepted integers. Parsing happens before the greeting loop, so invalid input produces no greetings.
Reference
Acknowledgements
This post was created with assistance from AI.