python · level 3 · unit 6 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
The words come in a funny order. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import argparse
parser = argparse.ArgumentParser(prog="greet")
parser.add_argument("name")
parser.add_argument("--times", type=int, default=1)
parser.add_argument("--shout", action="store_true")
args = parser.parse_args(["--shout", "Ana", "--times", "2"])
name = args.name
if args.shout:
name = name.upper()
print(name, args.times, args.shout)
your turn
Your turn. Order some pizzas from the command line.
Name the option --count in the first blank. Then pass a size of small or large, and a number of pizzas, in the list.
fix it
The discount crashes. Fix it!
- The error says text and a number were mixed. What type is
args.percent? - Command-line arguments always arrive as text unless you tell
argparseto convert them. - Add
type=intto the--percentline, then run.
nailed it
your tools take orders from the command line. :D
argparsereads, converts and checks command-line arguments.- Positional arguments are required. Options can have defaults.
- Pass a list to
parse_argsto try out your tool.
new words in your collection
- command line
- command-line argument
- argparse
- option
This lesson isn’t saved. A free account remembers every lesson you finish.