终止沙箱会释放沙箱资源。任务执行完成、发生不可恢复错误或超出业务等待时间时,都应主动终止沙箱。
终止当前沙箱
await sandbox.kill();Python 示例:
sandbox.kill()推荐在 finally 中释放资源:
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 {
await sandbox.commands.run("npm test");
} finally {
await sandbox.kill();
}Python 示例:
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:
sandbox.commands.run("python3 -m pytest")
finally:
sandbox.kill()和暂停的区别
kill() 用于结束沙箱生命周期;pause() 用于暂停并等待后续恢复。终止后不能再通过 Sandbox.connect() 回到同一个运行现场。
如果任务需要短时间等待用户继续操作,使用暂停与恢复。如果任务已经完成,使用终止。
该文章对您有帮助吗?