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 errorTypeScript 示例:
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。需要对外暴露服务时,先用后台命令启动服务,再通过公网访问获取访问地址。
该文章对您有帮助吗?