代码运行

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

我的收藏

前提条件

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

运行代码

您可以使用 run_code 方法来在沙箱内置的 jupyter server 中执行代码。
Python
from e2b_code_interpreter import Sandbox
# 创建沙箱实例
sandbox = Sandbox.create()
# 默认执行python代码
response = sandbox.run_code("print(\\"hello\\")")

支持多种语言

您可以指定代码的语言,支持 python, javascript, typescript, java, r, bash。
Python
response = sandbox.run_code("console.log(\\"hello\\")","javascript")

创建代码执行上下文

默认情况下,每个语言会运行在其默认的上下文中,同一上下文共享变量。
您可以通过 create_code_context 来创建上下文。
Python
ctx = sandbox.create_code_context(language="python")
您可以通过 context 参数来指定运行时上下文,需要注意,仅能设置 language 和 context 中的一个参数,两者互斥。
Python
response = sandbox.run_code("print(\\"hello\\")",context=ctx)

代码执行流式返回

代码执行可以流式返回,您可以通过指定回调函数来接收流式返回的数据。
Python
python_stream_code="""
import time
for i in range(10):
print(i,end='')
time.sleep(1)
"""
sandbox.run_code(
python_stream_code,
on_stdout=lambda data: print(data),
on_stderr=lambda data: print(data),
on_result=lambda data: print(data),
on_error=lambda data: print(data)
)

指定代码运行环境变量

您可以为代码运行指定环境变量。
Python
response = sandbox.run_code("print(\\"hello\\")",envs={"foo":"bar"})

指定代码执行超时时间

您可以为代码运行指定超时时间,在超过指定时间后终止代码运行。
Python

response = sandbox.run_code("print(\\"hello\\")",timeout=60) # 单位:秒