Lesson 05 · 45 minutes
Build a command-line tool that fails in a clear way
- Catch and raise exceptions without hiding a failure
- Write messages with the logging module
- Build a command-line tool with argparse that returns an exit code
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
Every night at 02:00 a scheduler runs your counting script and sends an alert when the script returns a code other than 0. Last night the log file was missing, the script printed a long traceback, and nobody looked at it. The night before, a bug made it print nothing and return 0, so the scheduler reported "all clear" while no check had run. Your task is to build a tool whose failures are loud, short and in the right place.
Recall
Lesson 4: why do you open a file with "with open(...) as handle"?
The with block closes the file when the block ends, also when an error happens inside it. A file that stays open can lose data that is still in the buffer.
Lesson 3: why does a function that only prints a result give None when you store its value?
print shows a value on the screen, but it does not give it back. A function without return gives back None. This lesson uses return for the exit code: main returns a number, and sys.exit hands it to the shell.
The idea
An exception is Python's way to stop normal flow when something goes wrong. raise starts one. try / except catches it. If nobody catches it, the program stops with a traceback and the exit code 1.
Two rules guide all error code:
- Catch the narrowest error that you can handle (
FileNotFoundError, notException). - Never catch an error and do nothing. Either fix the situation, or report it and stop.
Every program has two output streams. Standard output (stdout) carries its result, and standard error (stderr) carries messages about the run. Both show on the screen unless you redirect one (Linux Part 1, lesson 6). A logger writes messages with a level. Output meant for the person who reads the result goes to print, on standard output; messages about how the program is running go to the log, on standard error.
| Level | Use it for |
|---|---|
DEBUG | Detail for a developer. |
INFO | Normal events: "read 5000 lines". |
WARNING | Something odd, but the work goes on. |
ERROR | The work failed. |
An exit code is the number a program returns: 0 means success, anything else means failure. Other programs and shell scripts test it.
- Scheduler → Your tool: start with arguments
- Your tool: parse, count, log
- Your tool → Scheduler: exit code 0, 1, 2 or 3
- Scheduler → Alert: raise one when the code is not 0
Worked example
1. Raise and catch an exception
Create errors_demo.py in ~/krlab/python. The words:
try:starts a block that may fail.except ValueError as error:runs when aValueErrorhappens in it, anderrorholds the error.int(text)raisesValueErrorwhen the text is not a whole number.raise ValueError("message")starts an error of your own, with a message.from Nonedrops the confusing first traceback.{text!r}prints a value with quotes, so that an empty or odd value is visible.1 <= port <= 65535is a chained test: both parts must be true.
errors_demo.py
def to_port(text):
try:
port = int(text)
except ValueError:
raise ValueError(f"not a number: {text!r}") from None
if not 1 <= port <= 65535:
raise ValueError(f"port out of range: {port}")
return port
for value in ["22", "ssh", "70000"]:
try:
print(to_port(value))
except ValueError as error:
print("bad port:", error)python3 errors_demo.py22
bad port: not a number: 'ssh'
bad port: port out of range: 70000The function checks its input and raises an error with a clear message. The caller decides what to do.
2. Read the command line with argparse
Create countfailed.py. It reads a log, counts the failed logins and returns an exit code. The new parts:
argparsereads the command line, checks it, converts values and writes the help text.add_argument("logfile")is a required word.--maxis an option with a type (int) and a default.sys.exit(number)ends the program with that exit code.mainreturns the number, andsys.exithands it to the shell.main(argv=None)takes the words of the command line as an argument, so that a test can pass its own list. With no argument,argparsereadssys.argv.
countfailed.py
import argparse
import sys
def count_failed(path):
failed = 0
with open(path, encoding="utf-8", errors="replace") as handle:
for line in handle:
if "Failed password" in line:
failed += 1
return failed
def main(argv=None):
parser = argparse.ArgumentParser(description="Count failed SSH logins in a log file.")
parser.add_argument("logfile", help="path of the auth log")
parser.add_argument("--max", type=int, default=3, help="exit 1 when failures exceed this number")
args = parser.parse_args(argv)
failed = count_failed(args.logfile)
print("failed logins:", failed)
if failed > args.max:
print("above the limit of", args.max)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())The log of lesson 4 holds three failed logins, and the limit is 3. Run the tool with the default limit, with a lower limit and with no argument. Here is a command line with all its parts (-v comes in step 3):
python3 countfailed.py data/auth.log
echo "exit code: $?"
python3 countfailed.py data/auth.log --max 2
echo "exit code: $?"
python3 countfailed.py
echo "exit code: $?"failed logins: 3
exit code: 0
failed logins: 3
above the limit of 2
exit code: 1
usage: countfailed.py [-h] [--max MAX] logfile
countfailed.py: error: the following arguments are required: logfile
exit code: 2A missing argument is a usage error, and argparse handles it with the code 2. A missing file is not handled yet: python3 countfailed.py data/nothing.log ends with a long traceback that names FileNotFoundError. Step 3 fixes that.
3. Add logging and handle the missing file
Replace countfailed.py with the form below. The result stays on print. The progress messages now go to a log, and the tool handles the missing file:
logging.getLogger(name)makes a logger.basicConfigsets the level and the format once. The%(...)swords are fields of a log record. A log call takes its values as arguments ("%s", args.logfile;%sis a text and%dis a whole number), and Python builds the text only if the level is on.action="store_true"makes a switch with no value:-visTruewhen it is present.OSErroris the family of file errors, anderror.strerroris the plain reason.
countfailed.py
import argparse
import logging
import sys
log = logging.getLogger("countfailed")
def count_failed(path):
failed = 0
with open(path, encoding="utf-8", errors="replace") as handle:
for line in handle:
if "Failed password" in line:
failed += 1
return failed
def main(argv=None):
parser = argparse.ArgumentParser(description="Count failed SSH logins in a log file.")
parser.add_argument("logfile", help="path of the auth log")
parser.add_argument("--max", type=int, default=3, help="exit 1 when failures exceed this number")
parser.add_argument("-v", "--verbose", action="store_true", help="show debug messages")
args = parser.parse_args(argv)
logging.basicConfig(
level=logging.DEBUG if args.verbose else logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
log.debug("reading %s", args.logfile)
try:
failed = count_failed(args.logfile)
except OSError as error:
log.error("cannot read %s: %s", args.logfile, error.strerror)
return 3
log.info("read %s", args.logfile)
print("failed logins:", failed)
if failed > args.max:
log.warning("above the limit of %d", args.max)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())4. Run it on the good case and ask for detail
python3 countfailed.py data/auth.log
echo "exit code: $?"
python3 countfailed.py data/auth.log --max 2 -v
echo "exit code: $?"2026-11-21 15:10:44,016 INFO countfailed: read data/auth.log
failed logins: 3
exit code: 0
2026-11-21 15:10:44,106 DEBUG countfailed: reading data/auth.log
2026-11-21 15:10:44,106 INFO countfailed: read data/auth.log
failed logins: 3
2026-11-21 15:10:44,106 WARNING countfailed: above the limit of 2
exit code: 1Each log line has the parts that the format text asked for:
The tool found a real condition, so it says so with a warning and a non-zero code. A monitoring job can now act on $?. The result goes to standard output and the log goes to standard error. The symbol > sends standard output to a file, so only the result goes in:
python3 countfailed.py data/auth.log > result.txt
cat result.txt2026-11-21 15:10:44,194 INFO countfailed: read data/auth.log
failed logins: 3The log line still shows on the screen, because it is on standard error. The file result.txt holds only failed logins: 3.
5. Make it fail on purpose
A missing file is an expected failure, so the tool reports it in one line. The no-argument run is the same as in step 2.
python3 countfailed.py data/nothing.log
echo "exit code: $?"2026-11-21 08:36:35,117 ERROR countfailed: cannot read data/nothing.log: No such file or directory
exit code: 3The exit codes of this tool are 0 clean, 1 above the limit, 2 bad usage, 3 unreadable file. Write them in your README. Run python3 countfailed.py --help to see the help text that argparse made for you.
Your turn
Do the task of the scheduler. There is no code here: use what the worked example showed.
Save gen5.py in ~/krlab/python. It writes an invented authentication event log with a fixed seed, so every reader gets the same file. A line looks like this: Nov 21 11:02:00 krbox auth: account locked user=dave. You do not need to study this generator: it only makes the data.
gen5.py
import random
import sys
rng = random.Random(5)
USERS = ["alice", "bob", "carol", "dave", "erin"]
EVENTS = ["account locked", "account unlocked", "password changed", "login ok"]
with open(sys.argv[1], "w", encoding="utf-8") as out:
for minute in range(60):
event = rng.choices(EVENTS, [3, 2, 1, 6])[0]
user = rng.choice(USERS)
out.write(f"Nov 21 11:{minute:02d}:00 krbox auth: {event} user={user}\n")Run python3 gen5.py lock.log. Then write lockcheck.py, a tool with this contract:
- It takes the path of a log, and the option
--maxwith a whole number. The default of--maxis 5. - It counts the lines that contain
account locked. - It prints the number of those lines on standard output. It writes an
INFOmessage to the log for what it did. - It returns
0when the count is not above the limit, and1when it is above. - It returns
3and writes oneERRORline, with no traceback, when the file cannot be read. - A bad option value must give the code 2 (let
argparsedo it).
Run the tool with different options and read the exit code after each run. Then answer from your own terminal.
Check yourself
What is wrong with "except Exception: pass" around a file read?
It hides every error, including bugs such as a typo in a variable name, and the program goes on with no data. A scheduled check could report success when it checked nothing. Catch the specific error (OSError) and log it or stop.
Why does log.info("read %s", path) beat log.info(f"read {path}")?
With the first form Python formats the text only if the level is active. It also keeps the message pattern and the values apart, which helps tools that group log messages. The f-string builds the text every time.
A shell script runs "python3 tool.py && echo done". The tool printed an error and returned 0. What happens?
The script prints "done", because && tests the exit code and sees success. A tool must return a non-zero code on failure, or no other program can know.
Why does the tool print its findings with print but its progress with the logger?
The result is the output that another program may read from standard output. Log lines go to standard error, so tool.py > result.txt captures only the result. Mixing the two ruins the pipe.
Field notes
- Do not put a secret or raw user input in a log message without thought. An attacker who controls a user name can write a newline into it and forge a second log line (log injection). Log with
%r(log.info("user %r", name)) to show control characters as escapes. - Use
raise ... from errorto keep the cause, and a bareraiseinsideexceptto pass the error up after you log it. Do not useassertfor input checks: Python removes assertions when it runs with-O. - Add
--outputand--formatoptions before the tool has users. Reading from standard input when the path is-lets the tool work in a pipe. - Write logs as one event per line with a stable format, so a SIEM can parse them. For production, send them to a file or to
journaldand let the platform rotate them.logging.handlers.RotatingFileHandlerdoes simple rotation. argparsereturns exit code 2 for bad usage, as many Unix tools do. Choose your other codes on purpose and document them:grepreturns 0 for a match, 1 for no match and 2 for an error.