问:在go语言中,根据不同的操作系统,选择adb文件路径来进行执行,封装成一个函数
package main
import (
"fmt"
"os/exec"
"runtime"
)
// GetADBPath 根据操作系统获取 ADB 可执行文件的路径
func GetADBPath() string {
switch runtime.GOOS {
case "windows":
return "path/to/adb.exe" // 替换为实际的 ADB 路径
case "darwin":
return "/path/to/adb" // 替换为实际的 ADB 路径
case "linux":
return "/path/to/adb" // 替换为实际的 ADB 路径
default:
return "adb" // 默认情况下,假设 ADB 在 PATH 中
}
}
// ExecuteADBCommand 执行 ADB 命令并返回输出结果或错误
func ExecuteADBCommand(args ...string) (string, error) {
adbPath := GetADBPath()
cmd := exec.Command(adbPath, args...)
output, err := cmd.CombinedOutput()
return string(output), err
}
func main() {
// 示例:获取连接的设备列表
output, err := ExecuteADBCommand("devices")
if err != nil {
fmt.Printf("Error executing adb command: %v\n", err)
return
}
fmt.Println("Connected devices:\n", output)
// 示例:获取设备的电池状态(假设有设备连接)
output, err = ExecuteADBCommand("shell", "dumpsys", "battery")
if err != nil {
fmt.Printf("Error executing adb command: %v\n", err)
return
}
fmt.Println("Battery status:\n", output)
}
解释
导入所需包:
fmt:用于格式化输出。
os/exec:用于执行外部命令。
runtime:用于检测操作系统类型。
GetADBPath 方法:
GetADBPath 函数根据操作系统类型返回对应的 ADB 可执行文件路径。
使用 runtime.GOOS 检测操作系统类型。
根据不同的操作系统返回不同的 ADB 路径。
封装 ExecuteADBCommand 方法:
ExecuteADBCommand 函数调用 GetADBPath 获取 ADB 路径。
使用 exec.Command 创建一个 adb 命令,并传递参数。
使用 CombinedOutput 方法执行命令,并获取输出结果(包括标准输出和标准错误)。
返回输出结果和可能的错误。
示例使用:
在 main 函数中,调用 ExecuteADBCommand 方法获取连接的设备列表。
打印输出结果或错误信息。
示例中还展示了如何获取设备的电池状态。
注意事项
确保在 GetADBPath 函数中替换为实际的 ADB 路径。
确保你的环境中已经安装了 ADB,并且 ADB 命令可以在终端中全局执行。