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

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