Commands 是在沙箱中啟動進程的核心能力。Agent 通常用它完成環境檢查、依賴安裝、代碼測試、啟動服務和讀取命令輸出。
常用能力
-
sandbox.commands.run():運行命令,可同步等待結果,也可後台運行。 -
sandbox.commands.list():列出運行中的命令和 PTY 會話。 -
sandbox.commands.connect():串連已有後台命令。 -
sandbox.commands.send_stdin()(Python)/sandbox.commands.sendStdin()(TypeScript):向命令標準輸入寫入內容。 -
sandbox.commands.kill():終止運行中的命令。
最小樣本
Python 樣本:
from e2b import CommandExitException
try:
result = sandbox.commands.run("python3 --version")
print(result.stdout.strip())
except CommandExitException as error:
message = f"exit={error.exit_code}: {error.stderr}"
raise RuntimeError(message) from error
TypeScript 樣本:
import { CommandExitError } from "e2b";
try {
const result = await sandbox.commands.run("python3 --version");
console.log(result.stdout.trim());
} catch (error) {
if (error instanceof CommandExitError) {
throw new Error(`exit=${error.exitCode}: ${error.stderr}`);
}
throw error;
}
前台運行命令時,如果命令以非零狀態代碼退出,Python SDK 會拋出 CommandExitException,TypeScript SDK 會拋出 CommandExitError。異常對象包含退出碼、標準輸出和標準錯誤。
選擇合適的執行方式
短命令使用同步 run(),長任務使用後台命令,互動式任務使用 stdin 或 PTY。需要對外暴露服務時,先用後台命令啟動服務,再通過公網訪問擷取訪問地址。