Interactive terminal (PTY)
Use it for REPLs, TUIs, anything that asks questions, and for putting a live terminal in front of a user.
Open a session#
import { Sandbox } from 'e2b'
const sandbox = await Sandbox.create()
const terminal = await sandbox.pty.create({
cols: 80,
rows: 24,
envs: { MY_VAR: 'hello' },
cwd: '/home/user',
user: 'root',
onData: (data) => process.stdout.write(data),
})
await sandbox.pty.sendInput(terminal.pid, new TextEncoder().encode("echo 'hello world'\n"))
await sandbox.pty.sendInput(terminal.pid, new TextEncoder().encode('exit\n'))
const result = await terminal.wait()
console.log('Exit code:', result.exitCode)from e2b import Sandbox, PtySize
sandbox = Sandbox.create()
terminal = sandbox.pty.create(
size=PtySize(rows=24, cols=80),
envs={'MY_VAR': 'hello'},
cwd='/home/user',
user='root',
)
sandbox.pty.send_stdin(terminal.pid, b"echo 'hello world'\n")
sandbox.pty.send_stdin(terminal.pid, b"exit\n")
result = terminal.wait(on_pty=lambda data: print(data.decode(), end=''))
print('Exit code:', result.exit_code)A PTY session times out after 60 seconds by default. For a terminal that stays open, pass timeoutMs: 0 (JavaScript) or timeout=0 (Python).
Resize, reconnect, kill#
await sandbox.pty.resize(terminal.pid, { cols: 120, rows: 40 })sandbox.pty.resize(terminal.pid, PtySize(rows=40, cols=120))Disconnecting keeps the process running; reconnect by PID with a new output handler.
const pid = terminal.pid
await terminal.disconnect()
const reconnected = await sandbox.pty.connect(pid, {
onData: (data) => console.log(new TextDecoder().decode(data)),
})
await sandbox.pty.sendInput(pid, new TextEncoder().encode('echo world\n'))pid = terminal.pid
terminal.disconnect()
reconnected = sandbox.pty.connect(pid)
sandbox.pty.send_stdin(pid, b'echo world\nexit\n')
reconnected.wait(on_pty=lambda data: print(data.decode()))const killed = await sandbox.pty.kill(terminal.pid)killed = sandbox.pty.kill(terminal.pid)