Product case study · November 17, 2026
Ask Claude Code to stop a Python wrapper hiding command failures
Repair a Python command wrapper with Claude Code. Check stderr, nonzero exits and timeouts using small local processes and repeatable tests.
A command wrapper needs separate outcomes for success, failure and timeout. Test all three before using its output in another step.
Your script runs an export command, gets a line of text back, and continues. But the export printed that line before failing. The wrapper returned stdout and discarded the evidence that should have stopped the next step.
Give Claude Code this small repair job: return text only when the child exits successfully; otherwise preserve the failure. Add a timeout so a stalled child has a separate outcome. The useful result is a wrapper with a contract you can check outside the agent conversation.
You need Python 3.8 or newer, Bash on Linux, macOS or WSL, and an installed, signed-in Claude Code. Use a fresh practice folder. The Python baseline and reference repair below were tested locally; the Claude prompt is an authored exercise, not a recorded agent run. Official sources were checked November 17, 2026.
Build a wrapper that hides the error
Create the folder and deliberately incomplete runner.py:
command_lab=$(mktemp -d)
cd "$command_lab"
cat > runner.py <<'PY'
import subprocess
def run_text(argv, timeout=2):
result = subprocess.run(argv, capture_output=True, text=True)
return result.stdout
PY
The function accepts a timeout but never passes it on. It also ignores the return code. Python’s subprocess.run documentation describes check=True for raising on a nonzero exit and timeout for limiting the wait. Neither is enabled by this wrapper.
Save the following as test_runner.py. These fixtures launch the current Python interpreter, so you do not need an external export program, network connection or package installation.
import subprocess
import sys
import unittest
from runner import run_text
class RunnerTests(unittest.TestCase):
def command(self, source, *args):
return [sys.executable, "-c", source, *args]
def test_success(self):
result = run_text(self.command("print('ready')"))
self.assertEqual(result, "ready\n")
def test_failure_keeps_evidence(self):
command = self.command(
"import sys; print('partial'); "
"print('export failed', file=sys.stderr); sys.exit(7)"
)
with self.assertRaises(subprocess.CalledProcessError) as caught:
run_text(command)
self.assertEqual(caught.exception.returncode, 7)
self.assertEqual(caught.exception.stdout, "partial\n")
self.assertEqual(caught.exception.stderr, "export failed\n")
def test_timeout(self):
command = self.command("import time; time.sleep(1)")
with self.assertRaises(subprocess.TimeoutExpired):
run_text(command, timeout=0.1)
def test_argument_stays_one_argument(self):
value = "quarter one; literal text"
command = self.command("import sys; print(sys.argv[1])", value)
self.assertEqual(run_text(command), value + "\n")
if __name__ == "__main__":
unittest.main()
Run:
python3 -m unittest -v
The baseline passes two tests and fails two. It returns partial\n instead of raising for exit code 7, and waits through the one-second sleep instead of raising a timeout. That finite sleep keeps the broken exercise from hanging indefinitely.
The argument test protects the input shape: spaces and punctuation belong to one argument. It does not prove that arbitrary programs or arguments are safe to execute.
Ask Claude for the smallest repair
Start claude inside the practice directory. Verify the working directory and review tool permissions, then paste:
Read runner.py and test_runner.py. Run python3 -m unittest -v.
Explain why a failed child currently looks like usable output.
Change only runner.py. Preserve run_text(argv, timeout=2).
Accept an argument list and invoke it without a shell. On success,
return stdout as text. On a nonzero exit, propagate CalledProcessError
with return code, captured stdout and captured stderr. Pass timeout
through and propagate TimeoutExpired. Do not catch either exception
and return an empty string or partial output as success.
Use the Python standard library. Do not edit tests, install packages,
access external services, commit or delegate. Run the unchanged tests
and report their actual results. If execution is unavailable, say so.
Explain the limits for child processes that spawn descendants or
produce large output.
Anthropic’s common workflows includes debugging and testing recipes. This prompt supplies the reproduction, the allowed edit and the verification command together. Keep the test file visible during review: changing an assertion to accept partial output would remove the requirement rather than fix the wrapper.
The prompt is a work instruction, not a sandbox. Review tool requests and keep unrelated files out of this practice directory.
Compare the repair with the contract
A reference implementation is:
import subprocess
def run_text(argv, timeout=2):
result = subprocess.run(
argv,
capture_output=True,
text=True,
check=True,
timeout=timeout,
shell=False,
)
return result.stdout
capture_output=True retains both streams; text=True requests decoded text. check=True raises CalledProcessError for a nonzero exit, with captured output available on the exception. With run, an expired timeout kills and waits for the child before raising TimeoutExpired. Process creation itself can delay that outcome, so this is not a precise end-to-end stopwatch guarantee. These behaviors are documented in the Python subprocess reference.
Exit Claude and run the unchanged suite yourself:
python3 -m unittest -v
The reference repair passes all four tests. Python’s unittest documentation explains the exception assertions used here. The exit-error test checks the evidence carried by the exception, not merely that something went wrong.
Record your Python version, the test command, the test count and the actual output. Keep the failure run as well as the passing run. That pair shows which behavior the edit changed; a confident agent summary cannot replace it.
Handle failure at the caller without hiding it again
The wrapper deliberately leaves policy to its caller. An interactive tool might show a concise error. A batch job might record the status and stop. Neither should feed partial into the next operation as if it were a completed export.
Use this review checklist for the agent’s patch:
| Check | Evidence to inspect |
|---|---|
| Successful output still works | test_success passes with the exact newline preserved |
| Failed command stops normal return | Exit code 7 raises and carries both streams |
| Timeout is actually used | The sleeping child raises TimeoutExpired |
| Arguments retain their boundaries | The string with spaces and punctuation reaches the child intact |
Do not automatically retry the failed command. A process can make changes before returning an error or timing out. For a real export, inspect the destination and establish whether repeating the operation is safe first. Our fixtures only print or sleep; they do not test that recovery policy.
Know where this exercise ends
Keep this wrapper for trusted commands with small, bounded output. Capturing output holds it in memory. A timeout on the immediate child is not a general process-tree cleanup policy, and shell=False is not an authorization system. Consult Python’s security considerations before adapting the pattern to other platforms or command types.
If the first test raises FileNotFoundError, check the executable path. If importing runner fails, return to the folder containing both files. If the timeout test intermittently fails on an overloaded machine, inspect the actual exception and fixture before loosening its contract; do not replace it with an assertion that accepts success.
The next useful step is to apply this review to one existing wrapper: find where it decides success, locate what happens to stderr, and identify who owns retry decisions. Start with the Claude Code project-session lesson if you need help scoping that edit.
Sources and verification
Checked November 17, 2026:
- Python subprocess reference: command execution, captured output, exit errors, timeouts and limits.
- Python unittest reference: test discovery and exception assertions.
- Anthropic common workflows: debugging and testing with Claude Code.
The local checks cover the supplied Python examples only. They do not establish how Claude will respond, measure model performance, or validate a production command runner.
Put this to work
How stdout, stderr, exit status and timeout represent different evidence.
Try
Repair a tiny Python wrapper in a disposable practice folder.
Prove it worked
Keep the tests unchanged and confirm that failures raise instead of returning success-shaped text.
Keep in view
- Reproduce a wrapper that returns partial output after a failed command.
- Ask Claude Code to preserve exit errors and enforce a timeout.
- Verify the repair with four local subprocess tests.