沙箱实例

最近更新时间:2025-09-28 18:50:42

我的收藏

前提条件

在执行下文所有代码前,请先按照 配置环境变量 部分完成环境变量设置。
若您使用 e2b_code_interpreter sdk 且不指定 template,必须已在账号下创建名为 code-interpreter-v1 的代码解释器沙箱工具。

创建沙箱实例

Python
from e2b import Sandbox
from e2b_code_interpreter import Sandbox as CodeSandbox
# 创建一个沙箱工具名为"code-interpreter-v1"的沙箱实例
sandbox = Sandbox.create(template="code-interpreter-v1")
# 您也可以从e2b_code_interpreter中导入Sandbox,默认模板为"code-interpreter-v1"
sandbox = CodeSandbox.create()
# 您可以在创建时指定超时时间
# 当沙箱的运行时间超过超时时间时,沙箱将会被自动删除
sandbox = Sandbox.create(
template="code-interpreter-v1",
timeout=300 # 单位为秒
)
说明:
create 的 metadata,envs,secure,allow_internet_access 参数暂不可用,请期待后续功能更新。

获取沙箱实例列表

您可以使用 Sandbox.list() 获取到分页器,并使用分页器来以页为单位获取具体的沙箱实例信息。
Python
from e2b_code_interpreter import Sandbox
# 调用list方法获取分页器
paginator = Sandbox.list()
# 若分页器还有下一页,则取出下一页
while paginator.has_next:
page = paginator.next_items()
# 打印当前取出页的沙箱实例信息
for sandbox_info in page:
print(sandbox_info)
# 您可以指定一页中有多少实例
paginator_limit_5 = Sandbox.list(limit=5)
# 您可以获取当前分页器的偏移值
print(paginator_limit_5.next_token) # None
if paginator_limit_5.has_next:
paginator_limit_5.next_items()
print(paginator_limit_5.next_token) # offset_5

获取沙箱实例信息

您可以通过使用 get_info 方法来获取沙箱信息。
Python
from e2b_code_interpreter import Sandbox
# 创建沙箱实例
sandbox = Sandbox.create()
# 获取沙箱实例信息
info = sandbox.get_info()
print(info)
# 输出结果示例
# SandboxInfo(
# sandbox_id='1234567890qwertyuiopasdfghjklzxf',
# sandbox_domain=None,
# template_id='sdt-12345678',
# name='code-interpreter-v1',
# metadata={},
# started_at=datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=tzoffset(None, 28800)),
# end_at=datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=tzoffset(None, 28800)),
# state=<SandboxState.RUNNING: 'running'>,
# cpu_count=1, # 此处的cpu无实际意义,请使用云API查询沙箱的真实CPU设定
# memory_mb=2048, # 此处的memory无实际意义,请使用云API查询沙箱的真实内存设定
# envd_version='0.2.10',
# _envd_access_token='sit_12345678901234567890123456789012_1234567890'
# )

删除沙箱实例

Python
from e2b_code_interpreter import Sandbox
# 创建沙箱实例
sandbox = Sandbox.create()
# 删除沙箱实例
sandbox.kill()