Paul's Python CoursePPC

argparse reads the command line

Not met yet

argparse reads the command line for you. add_argument("customer") makes a required argument; a name starting -- makes an option. type=int converts, default= fills a gap, choices= limits the values, and action="store_true" makes a flag. parse_args() gives back an object with one attribute per argument, dashes turned into underscores. Missing or bad arguments get a usage message and exit code 2, and --help comes free.

Try it

main.py
import argparse

parser = argparse.ArgumentParser(description="Coffee for the class.")
parser.add_argument("days", type=int)
parser.add_argument("--cups", type=int, default=1)
args = parser.parse_args(["3", "--cups", "2"])  # as if typed after the name
print(f"{args.days * args.cups * 0.4:.1f} litres")

Output

Press Run and what your program prints shows up here.

Easy to get wrong

  • Thinks argparse always hands back text, even when the argument has type=int or type=float.
  • Thinks an option's default is used even when the option is given on the command line.
  • Thinks an option like --total-only is read as args.total-only, rather than args.total_only.

Where it comes up