background option to the commands.run() method. This will return immediately and the command will continue to run in the sandbox.
You can then later kill the command using the commands.kill() method.
Reconnect to a background command
A background command keeps running inside the sandbox even after the SDK disconnects. Because sandboxes are long-lived, you can start a long task in one process, return immediately, and reconnect from a completely different process later to wait for it and collect the result. This is a common pattern for kicking off slow work (code generation, a build, a data job) from a serverless function or API handler: you start the command, store the sandbox ID and process ID, and let a later request pick the work back up. The example below starts a long-running command (run-codegen here is a placeholder for your own binary or script) and returns the two identifiers you need to reconnect: the sandbox ID and the command’s process ID (pid).
- Redirect output to a file. The streamed
stdout/stderrfrom a background command is only delivered to the process that started it. Writing to a file (> /home/user/gen.log 2>&1) gives you durable output you can read after reconnecting. - Disable the command timeout.
timeoutMs: 0(timeout=0in Python) removes the command’s connection time limit so it isn’t killed while running long. Set the sandboxtimeoutMs/timeouthigh enough to outlast the whole job (15 minutes above). See sandbox persistence if you need it to survive even longer. - Persist the IDs. Return or store
sandboxIdandpid(for example in a database or the response of an API call). They are all a later process needs to callSandbox.connect()andcommands.connect().
commands.connect(pid) reattaches to the running command, and handle.wait() blocks until it finishes. If you don’t know the pid, you can look up running processes with sandbox.commands.list().