PTY 會建立偽終端會話,適合需要終端行為的工具,例如彩色輸出、Shell、互動式命令或依賴 TTY 判斷的 CLI。
建立 PTY 會話
TypeScript 樣本:
import { Sandbox } from "e2b";
const sandbox = await Sandbox.create("code-interpreter-v1", {
apiKey: process.env.E2B_API_KEY,
apiUrl: process.env.E2B_API_URL,
domain: process.env.E2B_DOMAIN,
});
try {
const terminal = await sandbox.pty.create({
cols: 80,
rows: 24,
timeoutMs: 0,
onData: (data) => {
process.stdout.write(data);
},
});
await sandbox.pty.sendInput(
terminal.pid,
new TextEncoder().encode("python3 - <<'PY'\nimport sys\nprint(sys.stdout.isatty())\nPY\n")
);
await sandbox.pty.sendInput(terminal.pid, new TextEncoder().encode("exit\n"));
const result = await terminal.wait();
console.log(result.exitCode);
} finally {
await sandbox.kill();
}Python 樣本:
import os
from e2b import PtySize, Sandbox
sandbox = Sandbox.create(
"code-interpreter-v1",
api_key=os.environ["E2B_API_KEY"],
api_url=os.environ["E2B_API_URL"],
domain=os.environ["E2B_DOMAIN"],
)
try:
terminal = sandbox.pty.create(
PtySize(rows=24, cols=80),
timeout=0,
)
sandbox.pty.send_stdin(
terminal.pid,
b"python3 - <<'PY'\nimport sys\nprint(sys.stdout.isatty())\nPY\n",
)
sandbox.pty.send_stdin(terminal.pid, b"exit\n")
result = terminal.wait(
on_pty=lambda data: print(data.decode(), end=""),
)
print(result.exit_code)
finally:
sandbox.kill()sandbox.pty.create() 會啟動互動式終端會話。TypeScript 使用 sandbox.pty.sendInput() 發送輸入,Python 使用 sandbox.pty.send_stdin() 發送輸入;通過 terminal.wait() 等待會話退出。需要斷開後重連時,儲存 terminal.pid,再使用 sandbox.pty.connect(pid)。
調整和終止 PTY
終端視窗大小變化時,調用 resize
TypeScript:
sandbox.pty.resize(pid, { cols, rows })。Python:
sandbox.pty.resize(pid, PtySize(rows, cols))
需要終止 PTY 會話時,調用
sandbox.pty.kill(pid)或會話對象的kill()。PTY 的輸入輸出走終端資料流,不適合依賴嚴格 stdout/stderr 分離的任務。
何時使用 PTY
適合使用 PTY 的情境:
需要類比真實終端行為的命令。
工具在非 TTY 環境下會關閉顏色、進度或互動能力。
需要給互動式進程發送標準輸入。
不建議使用 PTY 的情境:
只需要穩定解析 stdout/stderr 的批處理命令。
需要嚴格區分 stdout 和 stderr 的任務。
大量結構化日誌輸出情境。PTY 可能改變輸出格式,增加解析成本。
預設情況下,優先使用普通 commands.run()。只有命令明確依賴終端行為時,再使用 sandbox.pty。