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













