Run commands
import { Sandbox } from 'e2b'
const sandbox = await Sandbox.create()
const result = await sandbox.commands.run('ls -l')
console.log(result)from e2b import Sandbox
sandbox = Sandbox.create()
result = sandbox.commands.run('ls -l')
print(result)Stream output as it arrives#
Pass onStdout / onStderr (JavaScript) or on_stdout / on_stderr (Python).
const result = await sandbox.commands.run('echo hello; sleep 1; echo world', {
onStdout: (data) => console.log(data),
onStderr: (data) => console.log(data),
})result = sandbox.commands.run(
'echo hello; sleep 1; echo world',
on_stdout=lambda data: print(data),
on_stderr=lambda data: print(data),
)Run in the background#
const command = await sandbox.commands.run('echo hello; sleep 10; echo world', {
background: true,
onStdout: (data) => console.log(data),
})
await command.kill()command = sandbox.commands.run('echo hello; sleep 10; echo world', background=True)
for stdout, stderr, _ in command:
if stdout:
print(stdout)
if stderr:
print(stderr)
command.kill()Start a long job now, collect it later#
Return the sandbox ID and process ID right away, then reconnect from a different process (a worker, a webhook handler) and wait for the result.
Pass user input such as a prompt through envs, never by interpolating it into the shell string.
async function startGeneration(prompt: string) {
const sandbox = await Sandbox.create({ timeoutMs: 15 * 60_000 })
const handle = await sandbox.commands.run(
'run-codegen "$PROMPT" > /home/user/gen.log 2>&1',
{ background: true, timeoutMs: 0, envs: { PROMPT: prompt } }
)
return { sandboxId: sandbox.sandboxId, pid: handle.pid }
}
async function collectGeneration(sandboxId: string, pid: number) {
const sandbox = await Sandbox.connect(sandboxId)
const handle = await sandbox.commands.connect(pid)
await handle.wait()
return sandbox.files.read('/home/user/gen.log')
}def start_generation(prompt: str):
sandbox = Sandbox.create(timeout=15 * 60)
handle = sandbox.commands.run(
'run-codegen "$PROMPT" > /home/user/gen.log 2>&1',
background=True,
timeout=0,
envs={"PROMPT": prompt},
)
return {"sandbox_id": sandbox.sandbox_id, "pid": handle.pid}
def collect_generation(sandbox_id: str, pid: int):
sandbox = Sandbox.connect(sandbox_id)
handle = sandbox.commands.connect(pid)
handle.wait()
return sandbox.files.read("/home/user/gen.log")