liveBook · Manning

Argparse

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

argparse is a Python standard-library module for parsing command-line arguments and generating related usage and help information.

argparse is Python’s standard-library module for parsing command-line arguments, validating input, and generating usage and help messages. It supports positional arguments, named options, flags, defaults, and automatic -h/--help behavior. section 1.15 section 1.7

Use argparse to define and validate common command-line input patterns:

  • Require a positional value and receive a short usage error when it is missing. section 1.7
  • Accept zero or more or one or more values with nargs='*' or nargs='+'. section 6.1.1 section 6.5
  • Convert and validate values with type, including readable text files through argparse.FileType('rt'). section 6.3.1
  • Restrict an option to allowed values with choices and supply defaults for omitted options. section 8.3.1
  • Keep parsing and validation in a get_args() function, then pass the parsed namespace to main(). section 1.11

A small greeting command

import argparse def get_args(): parser = argparse.ArgumentParser(description='Say hello') parser.add_argument('-n', '--name', metavar='name', default='World', help='Name to greet') return parser.parse_args() def main(): args = get_args() print('Hello, ' + args.name + '!') if __name__ == '__main__': main() Running the program without -n uses World; running it with -n Terra prints Hello, Terra!. Running it with -h displays generated usage and help. section 1.11 section 1.7

#!/usr/bin/env python3
# Purpose: Say hello
 
import argparse
 
def get_args():                                                 #1
    parser = argparse.ArgumentParser(description='Say hello')
    parser.add_argument('-n', '--name', metavar='name',
                        default='World', help='Name to greet')
    return parser.parse_args()                                  #2
 
def main():                                                     #3
    args = get_args()                                           #4
    print('Hello, ' + args.name + '!')
 
if __name__ == '__main__':
    main()

Inspect the complete get_args()/main() listing for a compact, reusable argparse layout. section 1.11

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Explains positional, optional, flag, nargs, choices, type, and file arguments through repeated runnable programs, without internal implementation details.
Examples
Uses greeting commands, picnic lists, readable files, dictionary lookups, and vowel substitution to demonstrate argument definitions.
What it assumes
Assumes Python program structure and command-line execution while teaching argument types, validation, defaults, help, and usage from examples.
What you can do after
Build command-line programs that parse, validate, document, and organize user input with reusable get_args() functions.
How it connects
Connects command-line arguments with help messages, input validation, file handles, standard input, functions, and automated tests.

Also explained in

Compare how 3 books explain argparse →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.