终端命令
更新时间:2025-11-06
我们兼容了 E2B SDK,您可以使用 E2B SDK执行终端命令。
前提条件
- 请按照文档配置环境变量。
- 目前仅支持官方代码沙箱,即template名为 code-interpreter-v1。
在沙箱中运行终端命令
1from e2b_code_interpreter import Sandbox
2
3sandbox = Sandbox.create()
4
5result = sandbox.commands.run('ls -l')
6print(result)
1import { Sandbox } from '@e2b/code-interpreter'
2
3const sandbox = await Sandbox.create()
4const result = await sandbox.commands.run('ls -l')
5console.log(result)
运行终端命令并流式返回结果
1from e2b_code_interpreter import Sandbox
2
3sandbox = Sandbox.create()
4
5result = sandbox.commands.run('echo hello; sleep 1; echo world', on_stdout=lambda data: print(data), on_stderr=lambda data: print(data))
6print(result)
1import { Sandbox } from '@e2b/code-interpreter'
2
3const sandbox = await Sandbox.create()
4const result = await sandbox.commands.run('echo hello; sleep 1; echo world', {
5 onStdout: (data) => {
6 console.log(data)
7 },
8 onStderr: (data) => {
9 console.log(data)
10 },
11})
12console.log(result)
将终端命令放置在后台运行
1from e2b_code_interpreter import Sandbox
2
3sandbox = Sandbox.create()
4
5# 在后台运行命令,background参数设置为true
6command = sandbox.commands.run('echo hello; sleep 10; echo world', background=True)
7
8# 打印后台运行命令的标准输出和错误
9for stdout, stderr, _ in command:
10 if stdout:
11 print(stdout)
12 if stderr:
13 print(stderr)
14
15# 杀掉后台命令
16command.kill()
1import { Sandbox } from '@e2b/code-interpreter'
2
3const sandbox = await Sandbox.create()
4
5// 在后台运行命令,background参数设置为true
6const command = await sandbox.commands.run('echo hello; sleep 10; echo world', {
7 background: true,
8 onStdout: (data) => {
9 console.log(data)
10 },
11})
12
13// 杀掉后台命令
14await command.kill()
列出正在运行的后台命令
1command_list = sandbox.commands.list()
1const command_list = await sandbox.commands.list()
结束后台命令
1command_list = sandbox.commands.list()
2for command in command_list:
3 sandbox.commands.kill(command.pid)
1// 获取正在运行的命令列表
2const cmdList = await sandbox.commands.list();
3
4// 依次 kill 掉每一个命令
5for (const cmd of cmdList) {
6 await sandbox.commands.kill(cmd.pid);
7}
发送终端输入
您可以在代码中通过导入系统库来改变程序的环境变量,通过该种方式引入的环境变量在当前代码范围内生效。
1import asyncio
2async def send_stdin_test():
3 # 等待用户输入
4 read_code = """
5 echo test_stdin
6 read test
7 echo $test
8 """
9 # 执行命令
10 read_handler = sandbox.commands.run(read_code,background=True,stdin=True)
11 # 创建一个任务来等待命令完成并显示输出
12 wait_task = asyncio.create_task(
13 asyncio.to_thread(
14 read_handler.wait,
15 on_stdout=lambda data: print(data, end=""),
16 )
17 )
18 # 发送stdin
19 sandbox.commands.send_stdin(read_handler.pid,"input\n")
20 # 等待命令完成
21 response = await wait_task
22asyncio.run(send_stdin_test())
1待补充
