跟ChatGPT学习go语言-利用Go语言封装一个adb命令函数

问:在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 命令可以在终端中全局执行。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值