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


