执行命令
您可以在沙箱实例中执行终端命令,支持指定执行用户、设置环境变量、流式输出和超时控制。
前提条件
以下示例均基于E2B SDK,请确保已完成配置本地E2B SDK执行环境。
执行命令
您可以使用commands.run方法在沙箱实例中执行终端命令,同时commands.run方法支持以下扩展参数:
| 参数 | 说明 |
|---|---|
| user | 执行命令的用户身份。 |
| on_stdout | 标准输出回调函数,接收实时输出数据。 |
| on_stderr | 标准错误回调函数,接收实时错误数据。 |
| envs | 命令执行的环境变量,以字典形式传入。 |
| timeout | 命令执行的超时时间,单位为秒。超时后命令将被中断。 |
基本命令执行
您可以在沙箱实例中执行终端命令并获取输出结果,并且可以通过user参数指定执行命令的身份。
from e2b_code_interpreter import Sandbox
sandbox = Sandbox.create()
# 执行终端命令
response = sandbox.commands.run("ls")
print(response.stdout)
# 以root身份执行命令
response = sandbox.commands.run("ls", user="root")
print(response.stdout) 流式输出
对于长时间运行的命令,您可以通过on_stdout和on_stderr回调函数实时获取输出,无需等待命令执行完毕。
from e2b_code_interpreter import Sandbox
sandbox = Sandbox.create()
command = """
echo foo
sleep 1
echo bar
"""
# 通过回调函数实时获取标准输出和标准错误
sandbox.commands.run(
command,
on_stdout=lambda data: print(data),
on_stderr=lambda data: print(data)
) 查看环境变量
您可以通过envs字段为沙箱设置环境变量。
from e2b_code_interpreter import Sandbox
# 创建沙箱时设置环境变量
sandbox = Sandbox.create(
template="<template_id>",
envs={
"MY_VAR": "hello",
"MY_SECRET": "12345",
},
)
# 设置环境变量并执行命令
result = sandbox.commands.run("echo $MY_VAR")
print(result.stdout) # 输出: hello 设置命令超时时间
您可以通过timeout参数为命令执行设置超时时间,单位为秒。超时后命令将被中断。
from e2b_code_interpreter import Sandbox
sandbox = Sandbox.create()
# 设置超时时间为3秒,超时后命令将被中断
result = sandbox.commands.run("sleep 100", timeout=3) 完整代码示例
from e2b_code_interpreter import Sandbox
# 创建沙箱实例
sandbox = Sandbox.create(
template="<template_id>",
envs={
"MY_VAR": "hello",
"MY_SECRET": "12345",
},
)
# 执行终端命令
response = sandbox.commands.run("ls")
# 可以通过user参数指定执行命令的身份,支持user和root
response = sandbox.commands.run("ls",user="root")
# 支持流式返回
command = """
echo foo
sleep 1
echo bar
"""
# 您可以根据您的需要传递on_stdout和on_stderr回调
sandbox.commands.run(
command,
on_stdout=lambda data: print(data),
on_stderr=lambda data: print(data)
)
# 执行命令并设置所需环境变量
result = sandbox.commands.run("echo $MY_VAR")
assert "hello" in result.stdout
print(f"[PASS] run command with envs: {result.stdout.strip()}")
# 执行命令并设置命令运行超时时间
result = sandbox.commands.run("sleep 100", timeout=3) 相关文档
- 创建沙箱模板:了解如何创建自定义沙箱模板,预装所需的运行环境和依赖包。
- 创建API Key:了解如何创建和管理API Key,获取访问凭据。
- 创建网关实例:了解Agent网关的配置和管理,获取数据面访问地址。
- E2B SDK官方文档:了解E2B SDK的完整接口说明和更多用法示例。
- 如果在使用SDK时遇到连接失败、认证错误等问题,请先检查环境变量配置是否正确,特别是E2B_API_URL、E2B_SANDBOX_URL和E2B_API_KEY是否与控制台中的信息一致。