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

在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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里