Guides
Commands
Running a Command
Section titled “Running a Command”r = sbx.commands.run( "echo $MODE && ls /work", cwd="/work", envs={"EXTRA": "1"}, timeout=30, # seconds; None or 0 = no limit on_stdout=lambda s: print("live:", s, end=""),)print(r.exit_code, r.stdout)
# A list runs without a shell.r = sbx.commands.run(["python3", "-c", "import sys; print(sys.version)"])let r = await sbx.commands.run("echo $MODE && ls /work", { cwd: "/work", envs: { EXTRA: "1" }, timeoutMs: 30_000, // 0 = no limit onStdout: (s) => process.stdout.write(`live: ${s}`),});console.log(r.exitCode, r.stdout);
// An array runs without a shell.r = await sbx.commands.run(["python3", "-c", "import sys; print(sys.version)"]);res, err := sb.Commands.Run(ctx, "echo $MODE && ls /work", &sandbox.RunOptions{ Cwd: "/work", Envs: map[string]string{"EXTRA": "1"}, Timeout: 30 * time.Second, OnStdout: func(s string) { fmt.Print("live: ", s) },})if err != nil { return err}fmt.Println(res.ExitCode, res.Stdout)
// No shell: argv runs as-is.res, err = sb.Commands.RunArgs(ctx, []string{"python3", "-c", "import sys; print(sys.version)"}, nil)let res = sbx .commands .run_with( "echo $MODE && ls /work", RunOptions { cwd: "/work".into(), envs: HashMap::from([("EXTRA".into(), "1".into())]), timeout: Some(Duration::from_secs(30)), // Some(Duration::ZERO) = no limit on_stdout: Some(Box::new(|s| print!("live: {s}"))), ..Default::default() }, ) .await?;println!("{} {}", res.exit_code, res.stdout);
// No shell: argv runs as-is.let res = sbx .commands .run_args(["python3", "-c", "import sys; print(sys.version)"]) .await?;- A string runs with
bash -lc, so pipes,&&, globs and$VARSwork. This matches E2B. - An argv list runs as-is, with no shell (Python and TypeScript pass a list; Go uses
RunArgs, Rustrun_args). This matches Vercel’srunCommand(cmd, args)and Modal’sexec(*args). - Where it runs: commands run as root in
/workunless you givecwd. - The result has
exit_code/exitCode/ExitCode,stdoutandstderras text (UTF-8, with invalid bytes replaced).
Options
Section titled “Options”| Option | Python | TypeScript | Go | Rust | Default |
|---|---|---|---|---|---|
| Working directory | cwd= |
cwd |
Cwd |
cwd |
/work (relative paths resolve against it) |
| Environment variables | envs= |
envs |
Envs |
envs |
the sandbox’s envs |
| Time limit | timeout= (s; None/0 = none) |
timeoutMs (0 = none) |
Timeout (negative = none) |
timeout: Some(Duration) (Duration::ZERO = none) |
60 s |
| Standard input | stdin= (str/bytes) |
stdin (string/Uint8Array) |
Stdin []byte |
stdin: Vec<u8> |
empty |
| Live output | on_stdout=, on_stderr= |
onStdout, onStderr |
OnStdout, OnStderr |
on_stdout, on_stderr |
none |
| Detach | background=True |
background: true |
Start / StartArgs |
start / start_with / start_args_with |
— |
- Timeouts: the service enforces them, and kills the command when time is up.
- stdin: at most 16 MiB, sent up front and then closed. For more, write a file and redirect it.
- Output callbacks: called with each chunk as it arrives, in real time. The full output is also in the result. A character whose bytes arrive in two chunks is delivered whole, with the later chunk.
Errors
Section titled “Errors”A non-zero exit code is an error, as in E2B. The error carries the whole result:
try: sbx.commands.run("exit 3")except CommandExitError as e: print("exit code", e.exit_code, "stderr", e.stderr)
try: sbx.commands.run("sleep 10", timeout=1)except TimeoutError as e: print("timed out; partial output:", e.result.stdout if e.result else "")try { await sbx.commands.run("exit 3");} catch (e) { if (e instanceof CommandExitError) console.log("exit code", e.exitCode, "stderr", e.stderr);}try { await sbx.commands.run("sleep 10", { timeoutMs: 1000 });} catch (e) { if (e instanceof TimeoutError) console.log("timed out; partial output:", e.result?.stdout);}_, err = sb.Commands.Run(ctx, "exit 3", nil)var exit *sandbox.CommandExitErrorif errors.As(err, &exit) { fmt.Println("exit code", exit.ExitCode, "stderr", exit.Stderr)}var timeout *sandbox.TimeoutErrorif _, err := sb.Commands.Run(ctx, "sleep 10", &sandbox.RunOptions{Timeout: time.Second}); errors.As(err, &timeout) { fmt.Println("timed out; partial output:", timeout.Result.Stdout)}match sbx.commands.run("exit 3").await { Err(Error::CommandExit(r)) => println!("exit code {} stderr {}", r.exit_code, r.stderr), other => println!("{other:?}"),}let quick = RunOptions { timeout: Some(Duration::from_secs(1)), ..Default::default()};if let Err(Error::Timeout { result: Some(r), ..}) = sbx.commands.run_with("sleep 10", quick).await{ println!("timed out; partial output: {}", r.stdout);}| Situation | Python | TypeScript | Go | Rust |
|---|---|---|---|---|
| Exit code ≠ 0 | CommandExitError (.exit_code, .stdout, .stderr) |
CommandExitError (.exitCode, …) |
*CommandExitError |
Error::CommandExit(result) |
| Time limit passed | TimeoutError (.result = output so far) |
TimeoutError |
*TimeoutError |
Error::Timeout { result, .. } |
cwd doesn’t exist |
FileNotFoundError |
FileNotFoundError |
*NotFoundError (What: "directory") |
Error::NotFound (what: "directory") |
| An interactive shell is attached | SandboxBusyError |
SandboxBusyError |
ErrBusy |
Error::Busy |
| Connection ended or failed before the exit status | OutcomeUnknownError (.cause) |
OutcomeUnknownError (.cause) |
ErrOutcomeUnknown |
Error::OutcomeUnknown { cause, result } |
If you’d rather not get an exception for a failing command, append || true to the command or catch the
error. The error is also the result.
Background Commands
Section titled “Background Commands”A background command starts and returns at once. It keeps running after the call, across pauses, and while you run other commands:
server = sbx.commands.run("python3 -m http.server 8000", background=True)print("pid", server.pid)print("running:", server.poll() is None)print("killed:", server.kill())
job = sbx.commands.run("for i in 1 2 3; do echo $i; sleep 1; done", background=True)result = job.wait(on_stdout=lambda s: print(s, end=""))
# Or iterate over output chunks as they arrive:job = sbx.commands.run("for i in 1 2 3; do echo $i; sleep 1; done", background=True)for stdout, stderr in job: print(stdout or "", end="")const server = await sbx.commands.run("python3 -m http.server 8000", { background: true });console.log("pid", server.pid);console.log("running:", (await server.poll()) === undefined);console.log("killed:", await server.kill());
const job = await sbx.commands.run("for i in 1 2 3; do echo $i; sleep 1; done", { background: true });const result = await job.wait({ onStdout: (s) => process.stdout.write(s) });h, err := sb.Commands.Start(ctx, "python3 -m http.server 8000", nil)if err != nil { return err}fmt.Println("pid", h.PID)code, _ := h.Poll(ctx) // nil while runningfmt.Println("running:", code == nil)killed, _ := h.Kill(ctx)fmt.Println("killed:", killed)
job, _ := sb.Commands.Start(ctx, "for i in 1 2 3; do echo $i; sleep 1; done", nil)result, err := job.Wait(ctx, &sandbox.WaitOptions{OnStdout: func(s string) { fmt.Print(s) }})let server = sbx.commands.start("python3 -m http.server 8000").await?;println!("pid {}", server.pid);println!("running: {}", server.poll().await?.is_none());println!("killed: {}", server.kill().await?);
let job = sbx .commands .start("for i in 1 2 3; do echo $i; sleep 1; done") .await?;let result = job .wait_with(WaitOptions { on_stdout: Some(Box::new(|s| print!("{s}"))), ..Default::default() }) .await?;| Handle member | Python | TypeScript | Go | Rust |
|---|---|---|---|---|
| Process ID | pid |
pid |
PID |
pid |
| Wait for exit (raises on ≠ 0) | wait(on_stdout=, on_stderr=) |
wait({onStdout, onStderr}) |
Wait(ctx, *WaitOptions) |
wait(), wait_with(WaitOptions) |
| Check without waiting | poll() → code or None |
poll() → code or undefined |
Poll(ctx) → *int |
poll() → Option<i32> |
| Kill (SIGKILL to the whole process group) | kill() |
kill() |
Kill(ctx) |
kill() |
| Output so far | stdout, stderr |
stdout, stderr |
Stdout(), Stderr() |
stdout(), stderr() |
| Exit code once known | exit_code |
exitCode |
ExitCode() |
exit_code() |
Iterate (stdout, stderr) chunks |
for out, err in handle |
— | — | — |
Commands-level helpers:
commands.list()returns every background command started in the sandbox, with its pid, command line, and whether it’s running or its exit code.commands.connect(pid)gets a handle to a background command again, for example from another process.commands.kill(pid)kills one by pid.
How Background Output Works
Section titled “How Background Output Works”The service runs one command at a time per sandbox (see below), so a background command can’t stream its output over a held-open connection. Instead:
- Output: it goes to files in the sandbox (
/tmp/.chainguard-sandbox/cmd/<id>/). - Fetching:
wait()fetches the output in short polls, about every 2 s, and hands it to your callbacks. Output that an earlierpoll()fetched is delivered first. - Exit: a killed command’s exit code is
137(128 + SIGKILL).
One Command at a Time
Section titled “One Command at a Time”A sandbox runs one foreground command at a time. If you start two concurrently, the service queues
the second until the first finishes. This was measured live: two concurrent sleep 3 calls took 4 s and
7 s.
To do things in parallel inside one sandbox, start background commands; the short status calls interleave between them. Also:
- Exec vs. an interactive shell: commands are refused while an interactive shell
(
chainctl develop, or another Workspaces client) is attached to the same sandbox. You’ll getSandboxBusyError/ErrBusy/Error::Busy. - Retries: right after an attach or command ends, the service can briefly report the sandbox as held, and the library retries that for about 30 s.
