Loading WURK...
RomanMotion
RomanMotion
Product ad & launch videos · 3D product visuals · app & AI builder. Concept to final cut in days. Open for projects.

Build a small command-line tool with your coding agent: --help, exit codes and tests

A script isn't a tool until cron and other agents can trust it: --help, real exit codes, errors on stderr, and tests. Here's the prompt.

Published on November 11, 20266 min read

You asked your coding agent for a script, it worked, and you moved on. Then you put it in cron or handed it to another agent, and weeks later you found out it had been failing quietly the whole time: the job "ran", the exit code said success, and the error message sat in a log nobody reads. The fix is not more code, it's a contract, and your coding agent can build the whole thing from one prompt.

A script becomes a tool when other things can run it without you standing over it. That means five things: a --help that explains itself, arguments instead of hard-coded paths, exit code 0 when it worked and non-zero when it didn't, errors printed to stderr instead of mixed into the results, and a couple of tests that pin all of that down. Ask for exactly these, verify them once by hand, and the script stops being a one-off and becomes something you can schedule, chain, and hand to someone else.

Cron and agents read exit codes, not your print statements

When you run a script yourself, you watch the output and you notice when something goes wrong. Cron doesn't watch. Unless you've wired up mail or logs, nobody reads what the job printed, and the one signal a wrapper, a monitor or a shell && chain can check is the exit status. Coding agents lean on it too: they run a command, look at whether it failed, and decide what to do next.

So if your script prints "ERROR: file not found" but exits 0, every automated caller believes it succeeded. The pipeline continues on garbage. Nobody notices for weeks.

The other half of the contract is stdout versus stderr. Stdout is for results, stderr is for problems. When your script is one step in a chain (count.py notes.txt | upload.sh), whatever lands in stdout gets piped into the next step. If your error messages go there too, the next tool receives them as if they were data. Keep results and errors on separate streams and the chain stays honest.

Ask for the contract, not the vibe

The most common failure is a vague prompt: "make my script better." Your agent will add features. What you want is the interface. Paste something like this instead:

Turn my script count.py into a proper command-line tool:

- It counts lines, words or bytes in a text file.
- Arguments: one positional file path, plus a --count flag that
  accepts lines, words or bytes (default: words).
- --help: argparse-style help listing the argument, the flag and
  what each does.
- Exit codes: 0 when the count succeeded, 1 when the file is
  missing, argparse's own code (2) for invalid arguments.
- Output: the single number on stdout. Every error message goes
  to stderr and nothing else prints to stdout.
- Keep the counting logic in a function; add main(argv=None)
  that returns the exit code, so tests can call it directly.
- Tests: pytest tests that call main() with arguments, check the
  returned exit code, and use capsys to check what went to
  stdout and stderr. Include one test for the missing-file case.
- Do not add flags or features beyond what is listed above.

The last line matters more than it looks. Left alone, agents like to "improve" tools with extra flags, config files and progress bars. You asked for a contract; make it stick. This kind of tightly scoped prompt is where a good agent harness earns its keep, and if you want one to practise on, you can try the zcode agent harness free.

A minimal tool with argparse

Here is the shape you're asking for, small enough to read in one screen. The argparse module in the standard library builds the --help text and rejects bad flags for free, and sys.exit turns the return value into the process's real exit code:

#!/usr/bin/env python3
import argparse
import os
import sys


def count_in_file(path, mode):
    if mode == "bytes":
        return os.path.getsize(path)
    with open(path, "r", encoding="utf-8") as fh:
        text = fh.read()
    if mode == "lines":
        return text.count("\n")
    return len(text.split())


def main(argv=None):
    parser = argparse.ArgumentParser(
        description="Count lines, words or bytes in a text file."
    )
    parser.add_argument("file", help="path to the text file")
    parser.add_argument(
        "--count",
        choices=["lines", "words", "bytes"],
        default="words",
        help="what to count (default: words)",
    )
    args = parser.parse_args(argv)

    if not os.path.isfile(args.file):
        parser.exit(1, "error: file not found: %s\n" % args.file)

    print(count_in_file(args.file, args.count))
    return 0


if __name__ == "__main__":
    sys.exit(main())

Three details carry the whole contract. parser.exit(1, message) prints the message to stderr and ends the process with exit code 1, so the failure can never be mistaken for success. The choices= list makes argparse reject a bad --count value with its own error and exit code 2. And main(argv=None) returning a number on success instead of calling sys.exit itself is what makes the tool easy to test, which is the next section. (The failure paths still raise SystemExit, which the tests below catch with pytest.raises.)

Tests that pin the contract

A contract nobody checks is a comment, not a contract. With pytest, capsys captures stdout and stderr for you, so each test can assert both the exit code and which stream got what:

import pytest

from count import main


def test_counts_words(tmp_path, capsys):
    f = tmp_path / "notes.txt"
    f.write_text("one two\nthree\n", encoding="utf-8")
    assert main([str(f), "--count", "words"]) == 0
    assert capsys.readouterr().out.strip() == "3"


def test_counts_lines(tmp_path, capsys):
    f = tmp_path / "notes.txt"
    f.write_text("one two\nthree\n", encoding="utf-8")
    assert main([str(f), "--count", "lines"]) == 0
    assert capsys.readouterr().out.strip() == "2"


def test_missing_file_exits_1(tmp_path, capsys):
    with pytest.raises(SystemExit) as exc:
        main([str(tmp_path / "nope.txt")])
    assert exc.value.code == 1
    assert "nope.txt" in capsys.readouterr().err

The third test is the one that catches the classic bug. If a future edit moves the error message to stdout or drops the non-zero exit, this test fails immediately instead of failing silently in your cron log six weeks later.

Check it by hand once

Before you trust the tool, spend two minutes on the shell checks an automated caller would effectively repeat every run:

python3 count.py notes.txt            # 3
echo $?                               # 0
python3 count.py missing.txt          # error: file not found: missing.txt
echo $?                               # 1
python3 count.py missing.txt 2>/dev/null   # prints nothing: error was on stderr
python3 count.py notes.txt --count bogus; echo $?   # 2, with a usage line
python3 count.py --help

That 2>/dev/null line is the quick stdout-versus-stderr proof: if an error message still appears after stderr is discarded, the contract is broken.

These checks are cheap, but an agent that writes, tests and re-runs a tool like this does burn through usage. If you're choosing a plan for that kind of work, this link gets you 10% off GLM coding plans.

The checklist

Screenshot this and paste it into your next tool-building prompt:

  • Running with --help prints usage and exits 0
  • Inputs come in as arguments; nothing is hard-coded
  • Success exits 0, every failure path exits non-zero
  • Errors go to stderr, results to stdout
  • Bad input checked by hand: missing file, bad flag, each confirmed with echo $?
  • Tests call main() directly and check the exit code and both output streams
  • pytest passes on a fresh checkout with a single command

None of this is advanced engineering. It's a few lines of discipline that turn "a thing I run when I remember to" into "a thing the machine runs whether I remember to or not", which is the entire reason you wrote the script in the first place. More hands-on notes from building with coding agents are on our blog.

If this saved you an afternoon, a small tip on this post keeps these guides coming.

Conversation

Join the conversation

Share your thoughts with the author and other readers.

Comments0

Checking your account…

Latest comments

0
No comments yet. Be the first to share your thoughts.