liveBook · Manning

Command-line argument

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

A command-line argument is a value supplied to a program when it is launched from a command-line interface.

A command-line argument is a value supplied when a program starts, allowing its behavior to change without editing the program. Python's argparse module parses arguments and generates usage and help messages. section 1.7

Command-line arguments commonly take these forms:

  • Positional arguments, such as name, are usually required and have no default. section 1.8
  • Optional arguments, such as -n or --name, can be omitted and may provide a default value. section 1.8
  • Flags such as -h and --help request an action, commonly displaying usage documentation. section 1.7

Greeting a supplied name

Define a required name with argparse, then use it in the output. Running ./hello.py Terra produces Hello, Terra! Running ./hello.py without a name reports the required argument, while -h displays usage and help. section 1.7

Providing a default

Change the positional name to -n or --name and set default='World'. Then ./hello.py prints Hello, World!, while ./hello.py --name Terra prints Hello, Terra!. section 1.8

#!/usr/bin/env python3                                      #1
# Purpose: Say hello                                        #2
 
import argparse                                             #3
 
parser = argparse.ArgumentParser(description='Say hello')   #4
parser.add_argument('name', help='Name to greet')           #5
args = parser.parse_args()                                  #6
print('Hello, ' + args.name + '!')                          #7

The complete argparse-based greeting program shows the parser definition, required argument, parsing call, and use of the resulting value. section 1.7

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

How deep it goes
Explains parsing, help generation, positional and optional forms, and defaults, but stops short of parser internals.
Examples
Demonstrates greeting names, required and default values, help output, file inputs, and incremental tests.
What it assumes
Assumes basic Python and terminal execution while teaching argument parsing from a fixed-output program.
What you can do after
Build it from scratch, define argparse parameters, run programs with values or flags, and test usage and input behavior.
How it connects
Connects command-line arguments to argparse, help messages, positional arguments, optional arguments, flags, and automated testing.

Also explained in

Compare how 14 books explain command-line argument →

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.