Sub topic 9
Structuring the program around main(argv)
This chapter assumes you can write Python functions, handle exceptions, and run scripts from a terminal. It also assumes you know the basics of ArgumentParser, add_argument and parse_args from earlier chapters. Here the focus moves from individual arguments to the shape of the whole program.
Why a script needs a main function
A first argparse script often builds the parser at the top level of the file and does its work right below it. That works until you want to test it or import it. Importing the file runs the parser against whatever sys.argv happens to be, and a bad value calls sys.exit in the middle of your test run.
A main(argv=None) function fixes this. It takes the arguments as a parameter, parses them, does the work, and returns an integer exit code. Nothing runs at import time except definitions.
import argparse
import sys
def build_parser():
parser = argparse.ArgumentParser(prog="linecount", description="Count lines in files.")
parser.add_argument("paths", nargs="+", help="files to read")
parser.add_argument("--skip-blank", action="store_true",
help="do not count empty or whitespace-only lines")
return parser
def count_lines(path, skip_blank=False):
with open(path, encoding="utf-8") as handle:
if skip_blank:
return sum(1 for line in handle if line.strip())
return sum(1 for _ in handle)
def main(argv=None):
args = build_parser().parse_args(argv)
status = 0
for path in args.paths:
try:
total = count_lines(path, args.skip_blank)
except OSError as exc:
print(f"linecount: {path}: {exc.strerror or exc}", file=sys.stderr)
status = 1
continue
print(f"{total}\t{path}")
return status
if __name__ == "__main__":
raise SystemExit(main())Save this as linecount.py and run python linecount.py notes.txt missing.txt. The first file prints a count. The second prints an error on stderr, and the process exits with status 1.
The pieces and their jobs
The program has three layers, and each has one responsibility.
| Piece | Responsibility | Touches `sys.argv`? |
|---|---|---|
| `build_parser()` | Declares the interface and returns a fresh parser | No |
| `count_lines()` and other worker functions | Do the real work with ordinary Python values | No |
| `main(argv)` | Parses, calls workers, prints results, picks the exit code | Only through `argv=None` |
Keeping workers free of argparse and printing makes them easy to unit test and reuse from other code. main is the only place that knows about the terminal.
What argv=None really does
parse_args(None) is documented to read sys.argv[1:]. Passing None through is therefore the normal command-line path, and passing a list is the test path. You get both behaviors from one signature without writing any branching code.
The default is None instead of sys.argv[1:] because a default value is evaluated once, when the function is defined. Writing def main(argv=sys.argv[1:]) freezes the arguments at import time. Anything that changes sys.argv later, such as a test runner, would be ignored.
The empty-list trap
An empty list and None mean different things. main([]) means "run with no arguments". main(None) means "use the real command line". Do not write this:
def main(argv=None):
argv = argv or sys.argv[1:] # bug: [] is falsey
...With this code, main([]) silently reads the real command line, so a test meant to check the "no arguments" error would behave differently under a runner that was started with its own arguments. Pass argv straight to parse_args, or test with if argv is None.
The program name
When you run python linecount.py, argparse takes the name in usage messages from sys.argv[0]. Under python -m, a test runner, or an installed script, that name can differ or look odd. Setting prog="linecount" explicitly makes the usage line the same everywhere, which also keeps the output stable in tests.
Returning exit codes
By convention, status 0 means success and any non-zero value means failure. main returns the status as an integer, and the bottom of the file hands it to the interpreter:
if __name__ == "__main__":
raise SystemExit(main())SystemExit(0) and SystemExit(None) both exit with status 0, so a main that forgets to return anything still reports success. That is convenient for simple tools, but it makes failure paths easy to miss. Make every code path return a value on purpose.
sys.exit(main()) is equivalent. The raise SystemExit form is just more explicit about what happens.
Argparse follows the same convention internally. On a usage error it prints the usage line and a message to stderr and raises SystemExit(2). Your own errors should use a different non-zero value, usually 1, so a caller can tell "bad invocation" from "the work failed". The next chapter covers codes in more detail.
Keeping exits in one place
Calling sys.exit() from inside worker functions makes them hard to reuse and test. Raise ordinary exceptions from workers, then catch them in main and translate them to a message and a status. A small custom exception works well:
import argparse
import sys
class ToolError(Exception):
"""An expected failure that should be reported without a traceback."""
def load_threshold(text):
try:
value = float(text)
except ValueError:
raise ToolError(f"threshold must be a number, got {text!r}")
if value < 0:
raise ToolError("threshold must not be negative")
return value
def main(argv=None):
parser = argparse.ArgumentParser(prog="check")
parser.add_argument("threshold")
args = parser.parse_args(argv)
try:
value = load_threshold(args.threshold)
print(f"threshold is {value}")
return 0
except ToolError as exc:
print(f"check: error: {exc}", file=sys.stderr)
return 1
except KeyboardInterrupt:
print(file=sys.stderr)
return 130
if __name__ == "__main__":
raise SystemExit(main())Only ToolError is caught as an expected failure. Unexpected exceptions still produce a traceback, which is what you want for real bugs. The status 130 for KeyboardInterrupt follows the shell convention of 128 plus the signal number (SIGINT is 2).
Testing the shape you built
Because main takes a list and returns an integer, a test needs no subprocess and no patching of sys.argv:
from linecount import main
def test_counts_lines(tmp_path, capsys):
sample = tmp_path / "a.txt"
sample.write_text("one\n\ntwo\n", encoding="utf-8")
assert main([str(sample)]) == 0
assert capsys.readouterr().out == f"3\t{sample}\n"
def test_skip_blank(tmp_path, capsys):
sample = tmp_path / "a.txt"
sample.write_text("one\n\ntwo\n", encoding="utf-8")
assert main(["--skip-blank", str(sample)]) == 0
assert capsys.readouterr().out.startswith("2\t")
def test_missing_file_returns_1(tmp_path, capsys):
assert main([str(tmp_path / "nope.txt")]) == 1
assert "linecount:" in capsys.readouterr().errThe failure return is checked as a plain value. Only argparse's own errors need pytest.raises(SystemExit), because argparse exits instead of returning.
Common mistakes
- Parsing at import time. Any
parse_args()call outside a function breaks imports and tests. - Printing from workers. Output buried in helpers cannot be captured or reused. Return values and let
mainprint them. - Returning strings.
return "error"passes the string toSystemExit, which prints it to stderr and exits with status 1. This works, but it bypasses your own message format. Return integers. - Mutating
sys.argvin tests. Pass a list tomaininstead. - Forgetting the
__main__guard. Without it, importing the module runs the program.
Exercise
A teammate wrote def main(argv=sys.argv[1:]): and a test calling main([]) to check the "missing argument" error. The test passes, but the real command ignores arguments given in tests that set sys.argv through a runner. Explain the bug in the default, give the corrected signature, and say what main(None) does with it.
Show answer
The default sys.argv[1:] is evaluated once, when the function is defined, so it captures the arguments present at import time and never sees later changes. The fix is def main(argv=None): followed by parse_args(argv). With None, argparse reads sys.argv[1:] at call time, so it reflects the actual command line. main([]) still means "no arguments" and produces the missing-argument error with status 2.
Exercise
In the check tool above, what exit status does the shell see for each input: check 3.5, check abc, check -1, and check with no arguments?
Show answer
check 3.5 prints "threshold is 3.5" and exits with 0. check abc raises ToolError, prints an error to stderr, and exits with 1. check -1 is read by argparse as an unknown option rather than a value, so argparse itself exits with 2 (a value that starts with a dash needs -- before it). check with no arguments also exits with 2, because argparse reports the missing positional argument.