Codzy

Pro Python: building a command-line tool

Many professional scripts are launched in a terminal with options: python convert.py 50 --rate 1.1. The argparse module reads these arguments, checks their type, handles default values and builds a help page on its own (--help).

Each argument is declared with add_argument: a name without dashes is required (positional), a name with -- is an option. type=float converts the text, action="store_true" creates a switch. To test without a terminal, pass a list to parse_args([...]).

import argparse

parser = argparse.ArgumentParser(description="Greets someone")
parser.add_argument("name")
parser.add_argument("--times", type=int, default=1)
parser.add_argument("--shout", action="store_true")

args = parser.parse_args(["Lina", "--times", "2", "--shout"])
for _ in range(args.times):
    text = f"Hello {args.name}"
    print(text.upper() if args.shout else text)

Start the lesson