×

python · level 3 · unit 6 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

turns command-line words into checked values.

Real tools are started from a , like logcheck app.log --top 3. The words after the name are command-line arguments. The argparse module reads them, converts them and checks them, so your code only ever sees clean values.

add_argument("file") makes a positional argument that must be given. A name with two dashes, like --top, makes an , with a type, a default or a list of choices. action="store_true" makes a flag that is True when present.

Gwecode has no command line, so pass the words to parse_args as a list. It works the same way.

import argparse

parser = argparse.ArgumentParser(prog="logcheck")
parser.add_argument("file")
parser.add_argument("--top", type=int, default=5)
parser.add_argument("--level", choices=["INFO", "ERROR"], default="INFO")

args = parser.parse_args(["app.log", "--top", "3"])
print(args.file, args.top, args.level)
print(args.top * 2)

A real program calls parser.parse_args() with no list, and argparse reads whatever was typed.