get_args() is a reusable boundary for command-line input. It builds an argparse parser, defines the program’s arguments, validates them, and returns parsed values for main(). Keeping this function first makes the expected inputs easy to find and separates argument handling from program logic. section 1.11 section 2.3.1
Build get_args() incrementally:
- Create an argparse.ArgumentParser with a description. section 1.11
- Define meaningful positional arguments and optional flags; use nargs='+' for one or more values and action='store_true' for Boolean flags. section 2.1.4 section 3.6.1
- Use argparse types and choices for routine checks, then use parser.error() for constraints involving ranges, relationships, or occupied values. section 10.1 section 21.1.1
- Return parser.parse_args(), optionally transforming values such as reading file input and stripping trailing whitespace before main receives them. section 5.5.2 section 8.3.1
A small command-line boundary
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 a required argument produces usage and an error instead of returning incomplete input. section 1.11 section 2.3.1
#!/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()
Use the listing to inspect the complete separation between parser setup in get_args() and application behavior in main(). section 1.11
