Skip to content

Commands

sandbox.exec() runs a command in a sandbox to completion and returns its outputs and exit code. This page covers how a command is given, what it returns, its errors and deadlines, and the executions followed by their identifier. Commands that read standard input or stream their output are interactive sessions.

Running a command

The sandbox must run: commands go inside async with sandbox.running(): (see Sessions).

docs_src/client/commands.py
import fastsandbox
from fastsandbox.exceptions import CommandFailedError


async def main() -> None:
    client = await fastsandbox.connect()
    async with client.create(kit="shell") as sandbox, sandbox.running():
        # A string runs with `sh -c`; a list is the program and its arguments.
        output = await sandbox.exec("echo hello from $(hostname)")
        print(f"exit code {output.exit_code}: {output.stdout}", end="")
        await sandbox.exec(["ls", "-la", "/tmp"], check=True)

        # As root, in a directory, with variables and a deadline of its own.
        await sandbox.exec(
            ["make", "test"],
            user="0",
            working_dir="/work",
            env={"CI": "1"},
            timeout=600,
        )

        # A non-zero exit code is an output, not an error...
        failed = await sandbox.exec("exit 3")
        print(f"ok: {failed.ok}, exit code {failed.exit_code}")
        # ...unless the command is checked.
        try:
            await sandbox.exec("exit 3", check=True)
        except CommandFailedError as error:
            print(f"checked: exit code {error.exit_code}, stderr {error.stderr!r}")


if __name__ == "__main__":
    fastsandbox.run(main())

A command is given in one of three ways:

  • a string, run as a shell script with sh -c: POSIX sh, not a login shell, so a value put into the string is parsed by the shell; quote it with shlex.quote, or pass a list;
  • a list, the program and its arguments, not interpreted by a shell;
  • an ExecSpec, the full specification; ExecSpec.shell(script) builds one from a script. It holds the user, the working directory and the environment itself: exec() raises TypeError when user, working_dir or env comes along with it, while timeout and check still apply.
Argument Default What it sets
user the user of the kit a user name or UID; "0" for root
working_dir the working directory of the kit where the command runs
env none environment variables added to those of the sandbox
timeout the long-operation deadline of the client, 15 min how long the client waits for the execution, in seconds; it is not sent to the daemon
check False raises on a non-zero exit code

Outputs and exit codes

ExecOutput holds the exit_code, stdout and stderr of the command, as strings, and ok, whether it exited with 0.

A non-zero exit code is an output, not an error: the command ran. A program that does not exist is not an error either: it exits with code 127. check=True, or output.check() afterwards, turns a non-zero exit code into a CommandFailedError, which keeps exit_code, stdout and stderr; its message ends with the last lines of the standard error, or of the standard output when the error is empty.

The errors of the call itself are those of the daemon:

Exception When
SandboxTimeoutError the command did not end within its deadline; the deadline is the client's, so the process keeps running in the sandbox
ConflictError the sandbox is stopped
InvalidInputError the command is empty
NotFoundError the sandbox does not exist

Standard input

exec() sends no standard input. A command that reads it runs as an interactive session, whose collect() writes the input, closes it and gathers everything until the exit:

counted = await (await sandbox.attach(["wc", "-l"])).collect("one\ntwo\nthree\n")
print(counted.stdout.decode())  # bytes, as the command wrote them

Following an execution

An interactive execution has an identifier, Interactive.id, which a program can hand to another task. sandbox.exec_inspect(id) gives its state, an ExecInspect: whether it still runs, and its exit code once it ended. The daemon forgets an execution once its end has been reported: exec_inspect() then raises NotFoundError.

session = await sandbox.attach("sleep 1; exit 3")
state = await sandbox.exec_inspect(session.id)  # running
code = await session.wait()  # 3

The agent of the kit

sandbox.agent_session() starts the agent of the sandbox kit, with arguments as sbx run AGENT -- ARGS passes them: bash for the shell kit, a coding agent for the others. Without a terminal (tty=False, the default), its standard output and error come apart, as an unattended run needs them:

agent = await sandbox.agent_session(["-c", "echo out; echo err >&2"])
output = await agent.collect()

It returns an interactive session. To run a coding agent on a task, with its keys and network rules, see Agents.