Skip to main content

Start a background process

server = sandbox.commands.run(
    "python3 -m http.server 8080 --bind 0.0.0.0",
    shell=True,
    cwd="/workspace",
    background=True,
)
print(server.pid)
Without callbacks, background commands start through the REST exec endpoint and return once the guest process has a PID. The command continues running inside the sandbox until it exits, is killed, or the sandbox is paused or destroyed.

Fetch logs and stop

logs = sandbox.commands.get_logs(server.pid)
print(logs.stdout)

sandbox.commands.kill(server.pid)
result = server.wait()
print(result.exit_code)
Background command objects also expose kill():
server.kill()
BackgroundCommand also supports:
  • server.get_logs() to fetch stdout, stderr, interleaved output, and optional exit_code.
  • server.wait() to block until exit. If there is no live WebSocket attached, it polls the process list and then fetches logs.
  • server.disconnect() to close a live stream without killing the process.
  • Iteration over (stdout_chunk, stderr_chunk, None) tuples; this polls logs for new output.

Live background output

Pass callbacks with background=True when you want the process to keep running and stream output immediately:
def on_stdout(chunk: str) -> None:
    print(chunk, end="")

server = sandbox.commands.run(
    "python3 -u worker.py",
    shell=True,
    background=True,
    on_stdout=on_stdout,
)
server.disconnect()
This path uses the exec WebSocket to start the process and attach a reader to the returned PID.

Use with preview URLs

url = sandbox.get_url(8080)
print(url)
For web servers, bind to 0.0.0.0 inside the sandbox so preview URLs can reach the process.