创建沙箱是使用云沙箱的第一步。沙箱创建完成后,可以继续执行命令、读写文件、运行代码或启动临时 HTTP 服务。
创建默认沙箱
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 result = await sandbox.commands.run("echo hello");
console.log(result.stdout.trim());
} finally {
await sandbox.kill();
}Python 示例:
import os
from e2b import Sandbox
sandbox = Sandbox.create(
template="code-interpreter-v1",
api_key=os.environ["E2B_API_KEY"],
api_url=os.environ["E2B_API_URL"],
domain=os.environ["E2B_DOMAIN"],
)
try:
result = sandbox.commands.run("echo hello")
print(result.stdout.strip())
finally:
sandbox.kill()指定模板
当需要预装依赖或固定运行环境时,可以通过模板创建沙箱:
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,
timeoutMs: 10 * 60 * 1000,
});Python SDK 中,模板名称或模板 ID 通过 template 参数传入:
sandbox = Sandbox.create(
template="code-interpreter-v1",
api_key=os.environ["E2B_API_KEY"],
api_url=os.environ["E2B_API_URL"],
domain=os.environ["E2B_DOMAIN"],
timeout=10 * 60,
)TypeScript SDK 中,模板名称或模板 ID 通过 Sandbox.create(template, options) 的第一个参数传入。options 常用参数包括:
timeoutMs:沙箱超时时间,单位为毫秒。envs:写入沙箱运行环境的环境变量。metadata:写入沙箱控制面的自定义元数据。
使用建议
创建沙箱后,业务代码应在 try/finally 中主动调用 sandbox.kill()。对于需要保留现场的任务,可以使用暂停与恢复,但不要用暂停替代资源释放。
该文章对您有帮助吗?