在 Go 中为 CMD 执行 'cd' 命令

Execute the 'cd' command for CMD in Go

我想使用 Go 和 exec 库去某个路径,"c:",运行 一个 .exe 文件。

当我 运行 我的 Go 代码时,它给我:

exec: "cd:/": file does not exist

您为 运行 Cmd 对象中的命令指定初始工作目录:

cmd.Dir = "C:\"

有关详细信息,请参阅 documentation on the Cmd 结构。

cd 命令是 shell 的内置命令,无论是 bash、cmd.exe、PowerShell 还是其他命令。您不会执行 cd 命令然后执行您想要 运行 的程序。相反,您想设置 CmdDir 您将要 运行 包含程序的目录:

package main

import (
    "fmt"
    "log"
    "os/exec"
)

func main() {
    cmd := exec.Command("program") // or whatever the program is
    cmd.Dir = "C:/usr/bin"         // or whatever directory it's in
    out, err := cmd.Output()
    if err != nil {
        log.Fatal(err)
    } else {
        fmt.Printf("%s", out);
    }
}

在 运行 运行程序之前,请参阅 Cmd documentation for more information. Alternatively, you could use os/Chdir 更改工作目录。

根据命令是否需要在目录的“根”下操作,可以使用os.Chdir(dir)更改Go程序目录。所有后续命令和路径都将相对于提供给 os.Chdir.

dir 的值