Skip to content

Commands and PTY

sandbox.commands runs processes through the guest agent. A command runs under /bin/bash -l -c as the template’s default user.

from svm import Sandbox
with Sandbox.create(template="base") as sandbox:
result = sandbox.commands.run(
'echo "$GREETING from $(pwd)"',
envs={"GREETING": "hello"},
cwd="/tmp",
)
print(result.exit_code, result.stdout, result.stderr)
# A non-zero exit is not an exception: check exit_code.
failed = sandbox.commands.run("ls /does-not-exist")
if failed.exit_code != 0:
print(f"exit {failed.exit_code}: {failed.stderr.strip()}")

Callbacks get stdout and stderr as they arrive. The call still returns the complete result at the end.

from svm import Sandbox
with Sandbox.create(template="base") as sandbox:
result = sandbox.commands.run(
"for i in 1 2 3; do echo step $i; echo warning $i >&2; sleep 1; done",
on_stdout=lambda data: print("out:", data, end=""),
on_stderr=lambda data: print("err:", data, end=""),
)
print("exit code", result.exit_code)

background returns once the process starts, with a handle. You can wait on it, kill it, send it stdin, or disconnect from it and leave it running. Any client can list the sandbox’s processes and kill one by pid.

from svm import Sandbox
with Sandbox.create(template="base") as sandbox:
# stdin="" keeps the command's stdin open for send_stdin.
writer = sandbox.commands.run("cat > /tmp/notes.txt", background=True, stdin="")
server = sandbox.commands.run("python3 -m http.server 8000", background=True)
for process in sandbox.commands.list():
print(process.pid, process.cmd, process.args)
writer.send_stdin("written through stdin\n")
writer.close_stdin()
print("cat exited with", writer.wait().exit_code)
print(sandbox.files.read_text("/tmp/notes.txt"))
sandbox.commands.kill(server.pid) # or server.kill()

A PTY runs a shell with a terminal size. Write to it with send_input, change its size with resize, and receive its bytes in the data callback. To put it in a web page, pair it with xterm.js.

import time
from svm import Sandbox
with Sandbox.create(template="base") as sandbox:
terminal = sandbox.pty.create(
"bash",
cols=80,
rows=24,
on_data=lambda data: print(data, end=""),
)
sandbox.pty.send_input(terminal.pid, "echo hello from the terminal\n")
sandbox.pty.resize(terminal.pid, cols=120, rows=40)
sandbox.pty.send_input(terminal.pid, "tput cols\n") # 120
time.sleep(1) # on_data prints the output as it arrives
sandbox.pty.kill(terminal.pid)

Output is addressed by byte offset. When a stream breaks, the SDK reattaches from the offsets it has already seen, so no output is lost and none is repeated.

  • A foreground command whose caller gives up is killed, for example after an exception in a callback or a cancelled context.
  • The sandbox also kills a foreground process whose stream has been gone for 30 seconds.