Sub topic 9
Structuring the program around main(argv)
This chapter assumes you can build a parser with positional arguments and options, and that you know what exit codes are. Here you will put that parser inside a main(argv) function. The function takes an optional argument list and returns an exit code. A program built this way is easy to run, easy to test, and easy to install as a command.
Why a main function
A script that parses arguments at module level has three problems:
- Importing the file runs the parser immediately, so tests cannot import it.
- The parser always reads
sys.argv, so tests cannot feed it other input. - Errors end the process from deep inside the code, so callers cannot react to them.
A main(argv=None) function fixes all three. When argv is None, parse_args reads sys.argv[1:]. When you pass a list, it parses that list instead.
The pattern
import argparse
import sys
def build_parser():
parser = argparse.ArgumentParser(prog="greet", description="Print a greeting.")
parser.add_argument("name", help="who to greet")
parser.add_argument("-c", "--count", type=int, default=1,
help="number of times to greet (default: %(default)s)")
parser.add_argument("-v", "--verbose", action="store_true",
help="print extra information to stderr")
return parser
def main(argv=None):
args = build_parser().parse_args(argv)
if args.verbose:
print(f"Greeting {args.name} {args.count} time(s)", file=sys.stderr)
for _ in range(args.count):
print(f"Hello, {args.name}!")
return 0
if __name__ == "__main__":
raise SystemExit(main())Each part has one job:
build_parser()creates and returns the parser. It does no parsing, so you can inspect it or reuse it.main(argv=None)parses the list, does the work, and returns an integer.- The
if __name__ == "__main__":block runsmainonly when the file is executed directly, not when it is imported. raise SystemExit(main())turns the returned integer into the process exit status.SystemExit(0)means success, and any other integer means failure.
Notice that main returns the exit code instead of calling sys.exit itself. A test can then call main([...]) and compare the result with 0.
How the pieces flow
What argparse does on its own
When parse_args finds invalid input, it prints a usage message and an error to stderr, then raises SystemExit(2). You do not need to catch this in normal use. A test can catch it, as a later chapter shows.
--help also exits, with status 0, after printing the help text.
Passing arguments directly
Because main accepts a list, you can call it from other Python code or from an interactive session:
from greet import main
status = main(["Ada", "--count", "2"])
print("exit status:", status)This prints two greetings and then exit status: 0. The list holds only the arguments, without the program name. That matches sys.argv[1:].
Common mistakes
- Passing
sys.argvinstead ofsys.argv[1:]. The first item ofsys.argvis the program name. If you pass the whole list, it becomes a positional argument. - Calling
main()withoutraise SystemExit(...). The script still runs, but the shell always sees status 0, even ifmainreturned 1. - Building the parser at module level. Import side effects make tests slower and harder to isolate.
Exercise
A script ends with if __name__ == "__main__": main(). Its main returns 1 when a file is missing. The shell reports exit status 0 after a missing file. What is wrong, and what is the fix?
Show answer
The returned value is discarded, so the process exits with the default status 0. Change the last line to raise SystemExit(main()) so the returned integer becomes the exit status.
Exercise
Why does main(argv=None) default to None instead of an empty list?
Show answer
parse_args(None) reads sys.argv[1:], which is what a real run needs. An empty list would parse no arguments at all, so the program would ignore what the user typed.