go语言执行一个二进制程序时为什么写绝对路径反而不对啊?

cmd := exec.Command("./proxy")
cmd.Run()

比如写绝对路径程序是不会运行的,相对路径就可以

阅读 4.2k
3 个回答

从代码上看的话,应该是允许处理绝对路径的命令的:
os/exec/exec.go:117

// Command returns the Cmd struct to execute the named program with
// the given arguments.
//
// It sets only the Path and Args in the returned structure.
//
// If name contains no path separators, Command uses LookPath to
// resolve name to a complete path if possible. Otherwise it uses name
// directly as Path.
//
// The returned Cmd's Args field is constructed from the command name
// followed by the elements of arg, so arg should not include the
// command name itself. For example, Command("echo", "hello").
// Args[0] is always name, not the possibly resolved Path.
func Command(name string, arg ...string) *Cmd {
    cmd := &Cmd{
        Path: name,
        Args: append([]string{name}, arg...),
    }
    if filepath.Base(name) == name {
        if lp, err := LookPath(name); err != nil {
            cmd.lookPathErr = err
        } else {
            cmd.Path = lp
        }
    }
    return cmd
}

注释上说,如果name参数中含有路径分隔符(linux/unix 是/)则直接用提供的路径,如果不含有路径分隔符,会用环境变量中的path来取得最终的命令路径。

绝对路径程序是不会运行的这个结论是怎么得到的?不同意你这个结论。你提供的有价值信息太少,无法提供什么建议。

新手上路,请多包涵

常用这个功能,绝对路径是可以的,不过我用的较多的是macOS和Windows平台,都是可以用的

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题