gpt4 book ai didi

docker - 在没有 'which' 的情况下,以编程方式可靠地检索容器中 go 可执行文件的路径

转载 作者:数据小太阳 更新时间:2023-10-29 03:09:15 24 4
gpt4 key购买 nike

如何在没有 which 编程 的容器中检索到 go 二进制文件的路径?

一种选择是执行 which go 如下:

bytes, err := exec.Command("which", "go").Output()

但是,我不想依赖于 which 可用。 go 是否提供任何内置机制来检索它,如果没有,除了让用户自己传递路径之外还有什么替代方法?

最佳答案

来自man page of which :

Which takes one or more arguments. For each of its arguments it prints to stdout the full path of the executables that would have been executed when this argument had been entered at the shell prompt. It does this by searching for an executable or script in the directories listed in the environment variable PATH using the same algorithm as bash(1).

Go's os/exec.LookPath function非常接近这个功能:

LookPath searches for an executable named file in the directories named by the PATH environment variable. If file contains a slash, it is tried directly and the PATH is not consulted. The result may be an absolute path or a path relative to the current directory.

使用path/filepath.Abs如果您需要有保证的绝对路径。

关于docker - 在没有 'which' 的情况下,以编程方式可靠地检索容器中 go 可执行文件的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54902664/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com