简体   繁体   English

如何在 Go 的 $PATH 中获取可执行文件的完整路径

[英]How to get the full path of an executable in $PATH in Go

I would like have the functionality of which using Go.我想要which用 Go 的功能。

I would like to get the full path of some program in $PATH , or nothing if the program is not in $PATH .我想在$PATH $PATH ,则什么也没有。

I checked in the os package but I don't see anything relevant to achieve this functionality.我检查了os package 但我没有看到任何与实现此功能相关的内容。

My backup is exec.Command("which", "program") but that seems like overkill.我的备份是exec.Command("which", "program")但这似乎有点矫枉过正。

Use os/exec.LookPath :使用os/exec.LookPath

LookPath searches for an executable named file in the directories named by the PATH environment variable. LookPath 在由 PATH 环境变量命名的目录中搜索可执行的命名文件。 If file contains a slash, it is tried directly and the PATH is not consulted.如果文件包含斜杠,则直接尝试,不参考 PATH。 The result may be an absolute path or a path relative to the current directory.结果可能是绝对路径或相对于当前目录的路径。

Use path/filepath.Abs if you need the path to be absolute in all cases:如果在所有情况下都需要绝对路径,请使用path/filepath.Abs

package main

import (
    "log"
    "os/exec"
    "path/filepath"
)

func main() {
    fname, err := exec.LookPath("go")
    if err == nil {
        fname, err = filepath.Abs(fname)
    }
    if err != nil {
        log.Fatal(err)
    }

    log.Println(fname)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM