代码运行
更新时间 2026-05-11 16:54:02
最近更新时间: 2026-05-11 16:54:02
前提条件
在控制台完成沙箱模板创建。
在执行下文所有代码前,请先按照环境变量设置部分,完成环境变量设置。
运行代码
您可以使用 run_code 方法来在沙箱内置的 jupyter server 中执行代码。
from e2b_code_interpreter import Sandbox
# 注意:修改下面模板为您的模板名称或者模板id
sandbox = Sandbox.create(template="my_test_code_template")
# 默认执行python代码
response = sandbox.run_code("print(\"hello\")")支持多种语言
您可以指定代码的语言,支持 python, javascript, typescript, java, r, bash。
response = sandbox.run_code(
"console.log(\"hello\")",
"javascript"
)创建代码执行上下文
默认情况下,每个语言会运行在其默认的上下文中,同一上下文共享变量。
您可以通过 create_code_context 来创建上下文。
ctx = sandbox.create_code_context(language="python")您可以通过 context 参数来指定运行时上下文,需要注意,仅能设置 language 和 context 中的一个参数,两者互斥。
response = sandbox.run_code(
"print(\"hello\")",
context=ctx
)代码执行流式返回
代码执行可以流式返回,您可以通过指定回调函数来接收流式返回的数据。
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)
)指定代码运行环境变量
您可以为代码运行指定环境变量。
response = sandbox.run_code(
"print(\"hello\")",
envs={"foo": "bar"}
)指定代码执行超时时间
您可以为代码运行指定超时时间,在超过指定时间后终止代码运行。
response = sandbox.run_code(
"print(\"hello\")",
timeout=60 # 单位:秒
)