前提条件
在执行下文所有代码前,请先按照 配置环境变量 部分完成环境变量设置。
若您使用 e2b_code_interpreter sdk 且不指定 template,必须已在账号下创建名为 code-interpreter-v1 的代码解释器沙箱工具。
运行代码
您可以使用 run_code 方法来在沙箱内置的 jupyter server 中执行代码。
from e2b_code_interpreter import Sandbox# 创建沙箱实例sandbox = Sandbox.create()# 默认执行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 timefor 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) # 单位:秒