dqkx69935 2017-01-27 07:27 采纳率: 100%
浏览 336
已采纳

在Go中检查已安装的软件包

I need to check if some packages are installed but I need to do that using code, not go list tool in shell. I found a solution but it's very slow (2-3 seconds). This is my current code:

out, err := exec.Command("sh", "-c", "go list all").Output()
if err != nil {
    output := strings.Split(string(out), "
")
    for _, value := range output {
        if value == "github.com/some/package" {
            // package is installed
        }
    }
}
  • 写回答

1条回答 默认 最新

  • duanmanmian7589 2017-01-27 08:24
    关注

    So basically you answered your own question. You want a faster solution? Try "tuning" the go list command.

    To check the existence of a single package, you may pass that single package to go list, and if it exists, it will output it, else the output will be an error message.

    For example, executing

    go list github.com/some/package
    

    If github.com/some/package exists, output will be:

    github.com/some/package
    

    You can also pass multiple packages to go list:

    go list github.com/some/package github.com/other/package
    

    And output will be:

    github.com/some/package
    github.com/other/package
    

    If the passed package doesn't exist, output will be something like:

    can't load package: package github.com/some/package: cannot find package "github.com/some/package" in any of:
        /usr/local/go/src/github.com/some/package (from $GOROOT)
        <GOPATH-here>/src/github.com/some/package (from $GOPATH)
    

    Also note that if the package you pass does not contain *.go files, you get a different message:

    can't load package: package github.com/some/package: no buildable Go source files in <GOPATH-here>/src/github.com/some/package
    

    If you expect some package inside it, append the ...:

    go list github.com/some/package/...
    

    For more options and possibilities, run go help list, and see related question: How to list installed go packages

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器