Command-line tools with argparse

Turning a script into a tool with options, defaults, types and a free --help page.

What you'll learn
  • Declare typed options with defaults and help text
  • Use store_true flags
  • Guard a script's entry point with if __name__ == '__main__'

A script that reads its settings from the command line can be reused without editing it. argparse, in the standard library, turns a few declarations into a parser with type checking, defaults and a generated help page:

parser = argparse.ArgumentParser(description="A simple python script ...")
parser.add_argument('--name', type=str, default='World', help='...')
parser.add_argument('--repeat', type=int, default=1, help='...')
parser.add_argument('--verbose', action='store_true', help='Enable verbose mode')
args = parser.parse_args()
python3 arg_parser.py --name Ada --repeat 2 --verbose
# Hello, Ada! (Verbose mode enabled)
# Hello, Ada! (Verbose mode enabled)
python3 arg_parser.py --repeat two
# arg_parser.py: error: argument --repeat: invalid int value: 'two'
python3 arg_parser.py --help

type=int converts the text and rejects anything that is not an integer, with a proper usage message and exit status 2. action='store_true' makes a flag that takes no value: present means True. And --help comes free, built from the help= strings.

The script prints the greeting once and then args.repeat - 1 more times. That has a quiet edge case: --repeat 0 still prints once, because the first print is unconditional. Looping for _ in range(args.repeat) matches the option’s name, and a custom check — or type=positive_int with a small validation function — rejects negative counts outright.

The main guard

if __name__ == '__main__':
    main()

When a file runs as a script, Python sets __name__ to '__main__'; when it is imported, __name__ is the module’s name. The guard lets the same file be a tool and a library: importing it to reuse main does not suddenly parse the importer’s command line.

Try it yourself. Add a positional argument greeting with choices=['Hello', 'Hi', 'Servus'], and a --shout flag that upper-cases the output. Check what --help now prints, and what happens with --repeat -1.

View source on GitHub →