描述
Command 类提供在 AgentBay 云环境会话中执行命令的方法。
方法 | 说明 | 环境 | ||||
ComputerUseLinux | ComputerUseWindows | BrowserUse | MobileUse | CodeSpace | ||
| 在云环境中执行命令 | 支持 | 支持 | 支持 | 支持 | 支持 |
| 执行Shell命令(带超时控制) | 不支持 | 不支持 | 不支持 | 不支持 | 支持 |
方法
ExecuteCommand
- 执行命令
Golang
func (cmd *Command) ExecuteCommand(command string, timeoutMs ...int) (*CommandResult, error)
参数:
command(string):要执行的命令。
timeoutMs(int,可选):命令执行的超时时间(毫秒)。默认为
1000ms
。
返回值:
*CommandResult
:包含命令输出和请求ID的结果对象。error
:若命令执行失败,返回错误信息。
CommandResult 结构体:
type CommandResult struct {
RequestID string // 调试用的唯一请求标识符
Output string // 命令的输出
}
Python
def execute_command(command: str, timeout_ms: int = 1000) -> OperationResult
参数:
command(str):要执行的命令。
timeout_ms(int,可选):命令执行的超时时间(毫秒)。默认为1000ms。
返回值:
OperationResult
:包含命令输出(data)、操作状态、请求ID和错误信息的结果对象。
TypeScript
executeCommand(command: string, timeoutMs: number = 1000): Promise<string>
参数:
command(string):要执行的命令。
timeoutMs(number,可选):命令执行的超时时间(毫秒)。默认为
1000ms
。
返回值:
Promise<string>
:返回命令输出结果的Promise。
异常:
Error
:若命令执行失败,抛出错误。
RunCode
- 运行代码
Golang
func (cmd *Command) RunCode(code string, language string, timeoutS ...int) (*CommandResult, error)
参数:
code(string):要执行的代码。
language(string):代码的编程语言。必须为
python
或javascript
。timeoutS(int,可选):代码执行的超时时间(秒)。默认为
300s
。
返回值:
*CommandResult
:包含代码执行输出和请求ID的结果对象。error
:若代码执行失败或指定了不支持的语言,返回错误信息。
Python
def run_code(code: str, language: str, timeout_s: int = 300) -> OperationResult
参数:
code(str):要执行的代码。
language(str):代码的编程语言。必须为
python
或javascript
。timeout_s(int,可选):代码执行的超时时间(秒)。默认为
300s
。
返回值:
OperationResult
:包含代码执行输出(data)、操作状态、请求ID和错误信息的结果对象。
TypeScript
runCode(code: string, language: string, timeoutS: number = 300): Promise<string>
参数:
code(string):要执行的代码。
language(string):代码的编程语言。必须为
python
或javascript
。timeoutS(number,可选):代码执行的超时时间(秒)。默认为
300s
。
返回值:
Promise<string>
:返回代码执行输出结果的Promise。
异常:
APIError
:若代码执行失败或指定了不支持的语言,抛出错误。
使用示例
Golang
执行命令
package main
import (
"fmt"
"log"
)
func main() {
// 创建会话
agentBay := agentbay.NewAgentBay("your-api-key")
sessionResult, err := agentBay.Create(nil)
if err != nil {
log.Fatal(err)
}
session := sessionResult.Session
// 执行命令(默认超时 1000ms)
result, err := session.Command.ExecuteCommand("ls -la")
if err != nil {
log.Printf("Error executing command: %v", err)
} else {
fmt.Printf("Command output: %s\n", result.Output)
}
// 执行命令(自定义超时 2000ms)
resultWithTimeout, err := session.Command.ExecuteCommand("ls -la", 2000)
if err != nil {
log.Printf("Error executing command with timeout: %v", err)
} else {
fmt.Printf("Command output with timeout: %s\n", resultWithTimeout.Output)
}
}
运行代码
package main
import (
"fmt"
"log"
)
func main() {
// 创建会话
agentBay := agentbay.NewAgentBay("your-api-key")
sessionResult, err := agentBay.Create(nil)
if err != nil {
log.Fatal(err)
}
session := sessionResult.Session
// 执行 Python 代码
pythonCode := `
print("Hello, world!")
x = 1 + 1
print(x)
`
result, err := session.Command.RunCode(pythonCode, "python")
if err != nil {
log.Printf("Error running Python code: %v", err)
} else {
fmt.Printf("Python code output: %s\n", result.Output)
}
// 执行 JavaScript 代码(自定义超时 600s)
jsCode := `
log("Hello, world!");
const x = 1 + 1;
log(x);
`
resultJS, err := session.Command.RunCode(jsCode, "javascript", 600)
if err != nil {
log.Printf("Error running JavaScript code: %v", err)
} else {
fmt.Printf("JavaScript code output: %s\n", resultJS.Output)
}
}
Python
from agentbay import AgentBay
# 初始化 SDK
agent_bay = AgentBay(api_key="your_api_key")
# 创建会话
session_result = agent_bay.create()
if session_result.success:
session = session_result.session
# 执行命令(默认超时 1000ms)
result = session.command.execute_command("ls -la")
if result.success:
print(f"命令输出: {result.data}")
else:
print(f"命令执行失败: {result.error_message}")
# 执行命令(自定义超时 2000ms)
result_with_timeout = session.command.execute_command("ls -la", timeout_ms=2000)
if result_with_timeout.success:
print(f"自定义超时命令输出: {result_with_timeout.data}")
else:
print(f"命令执行失败: {result_with_timeout.error_message}")
# 执行 Python 代码
python_code = """
print("Hello, world!")
x = 1 + 1
print(x)
"""
result_code = session.command.run_code(python_code, "python")
if result_code.success:
print(f"Python 代码执行结果: {result_code.data}")
else:
print(f"代码执行失败: {result_code.error_message}")
# 执行 JavaScript 代码(自定义超时 600s)
js_code = """
log("Hello, world!");
const x = 1 + 1;
log(x);
"""
result_js = session.command.run_code(js_code, "javascript", timeout_s=600)
if result_js.success:
print(f"JavaScript 代码执行结果: {result_js.data}")
else:
print(f"代码执行失败: {result_js.error_message}")
TypeScript
import { AgentBay } from 'wuying-agentbay-sdk';
// 初始化 SDK
const agentBay = new AgentBay({ apiKey: 'your_api_key' });
// 创建会话
async function createSession() {
try {
const sessionResult = await agentBay.create();
const session = sessionResult.session;
// 执行命令(默认超时 1000ms)
const commandOutput = await session.command.executeCommand('ls -la');
console.log(`命令输出: ${commandOutput}`);
// 执行命令(自定义超时 2000ms)
const commandOutputWithTimeout = await session.command.executeCommand('ls -la', 2000);
console.log(`自定义超时命令输出: ${commandOutputWithTimeout}`);
// 执行 Python 代码
const pythonCode = `
print("Hello, world!")
x = 1 + 1
print(x)
`;
const pythonResult = await session.command.runCode(pythonCode, 'python');
console.log(`Python 代码执行结果: ${pythonResult}`);
// 执行 JavaScript 代码(自定义超时 600s)
const jsCode = `
log("Hello, world!");
const x = 1 + 1;
log(x);
`;
const jsResult = await session.command.runCode(jsCode, 'javascript', 600);
console.log(`JavaScript 代码执行结果: ${jsResult}`);
} catch (error) {
console.error('操作失败:', error);
}
}
createSession();