Tutorials · Claude Agent SDK · examples / python / 21_sandbox_and_stderr.pyExample code

Example code · python

21_sandbox_and_stderr.py

Sandbox settings on a host WITHOUT bubblewrap: failIfUnavailable=True stops the run with a clear

Raw fileDownload all examples (zip)See its output →

Used in Part 3 §6 · Sandboxing and security hardening

"""21: Sandbox settings on a host WITHOUT bubblewrap: failIfUnavailable=True stops the run with a clear
error result; failIfUnavailable=False falls back with a warning you can capture through the stderr callback."""

import asyncio

from claude_agent_sdk import ClaudeAgentOptions, ResultError, ResultMessage, query
from demo_util import PROJECT


async def run(label, sandbox):
    print(f"\n=== {label} ===")
    stderr_lines = []
    try:
        async for m in query(
            prompt="Run `echo sandbox-test` with bash and reply with its output only.",
            options=ClaudeAgentOptions(cwd=PROJECT, allowed_tools=["Bash"], max_turns=3,
                                       sandbox=sandbox, stderr=stderr_lines.append),
        ):
            if isinstance(m, ResultMessage):
                print(f"result: subtype={m.subtype} terminal_reason={m.terminal_reason!r} errors={m.errors}")
                if m.result:
                    print(f"result text: {m.result!r}")
    except ResultError as e:
        print(f"ResultError raised: {e}")
    sandbox_lines = [l for l in stderr_lines if "sandbox" in l.lower()]
    print(f"stderr lines mentioning sandbox ({len(sandbox_lines)}):")
    for l in sandbox_lines[:4]:
        print("   ", l.strip()[:160])


async def main():
    await run("sandbox enabled, failIfUnavailable=True",
              {"enabled": True, "autoAllowBashIfSandboxed": True, "failIfUnavailable": True})
    await run("sandbox enabled, failIfUnavailable=False (fall back unsandboxed, warn)",
              {"enabled": True, "autoAllowBashIfSandboxed": True, "failIfUnavailable": False})


asyncio.run(main())

39 lines · Back to the folder