Sub topic 1
How a command-line program receives input and reports results
Prerequisites
This chapter assumes you can write and run Python scripts, define functions, handle exceptions, and use a terminal shell. You do not need to know argparse yet. This chapter covers the mechanics that argparse builds on.
What a command-line program sees
When you run a command, the shell splits the line into words and starts the program with those words. In Python, they arrive as a list of strings in sys.argv. The first item is the script name. The rest are the arguments you typed.
import sys
print(sys.argv)Save this as show_args.py and run python show_args.py hello -n 3 --flag. The output is:
['show_args.py', 'hello', '-n', '3', '--flag']Two points matter for later chapters:
- Every item is a string. The
3is the text"3", not an integer. - The shell does the splitting. Quotes group words, so
"two words"arrives as one item.
Reading sys.argv by hand works for tiny scripts. It does not scale. You would have to detect options, convert types, produce help text and report mistakes yourself. That is the work argparse takes over.
Three channels out: stdout, stderr and the exit code
A program reports results through three separate channels.
| Channel | Python access | Purpose |
|---|---|---|
| Standard output (stdout) | `print()`, `sys.stdout` | The program's normal results |
| Standard error (stderr) | `sys.stderr` | Diagnostics, warnings and errors |
| Exit code | `raise SystemExit(n)` or `sys.exit(n)` | A number telling the caller whether it worked |
Keeping stdout and stderr apart lets users redirect them independently. With python tool.py > result.txt, only stdout goes to the file. Error messages still appear on the terminal. If you print errors to stdout, they end up mixed into the data.
The exit code is an integer from 0 to 255. By convention, 0 means success and any other value means failure. Shells and scripts use it directly. For example, tool && echo done prints done only when the exit code is 0.
If a script ends normally, Python exits with 0. If an uncaught exception ends it, Python exits with 1. You can choose the value yourself:
import sys
def main():
if len(sys.argv) != 2:
print("usage: check.py NAME", file=sys.stderr)
return 2
print(f"Checking {sys.argv[1]}")
return 0
if __name__ == "__main__":
raise SystemExit(main())Run it with no arguments, then read the exit code. In bash, $? holds the code of the last command:
python check.py
echo $?The usage line goes to stderr and echo prints 2. The convention of using 2 for wrong usage comes from Unix tools, and argparse follows it.
The flow of one run
Common mistakes
- Treating arguments as typed values. Convert them yourself, or let argparse do it.
- Printing error messages with plain
print(). They then pollute output that another program may be reading. - Returning a value from
main()but never passing it toSystemExit. The process then exits with 0 even after a failure. - Using
sys.exit("message"). A string argument is printed to stderr, but the exit code is 1, which may not be the code you want.
Exercise
A script prints its results with print() and its error messages with print(..., file=sys.stderr). A user runs python tool.py > out.txt and the input is invalid. What appears in out.txt and what appears on the terminal?
Show answer
Nothing is written to out.txt, because the error message went to stderr and the redirect > captures only stdout. The error message appears on the terminal. If the script also returns a nonzero exit code, the shell records it in $?.