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

2023-12-26

我想使用 Go 和 exec 库转到某个路径,"c:",然后运行 ​​.exe 文件。

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

exec: "cd:/": 文件不存在


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

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);
    }
}

See the 命令文档 https://golang.org/pkg/os/exec/#Cmd了解更多信息。或者,您可以使用os/Chdir https://golang.org/pkg/os/#Chdir在运行程序之前更改工作目录。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Go 中执行 CMD 的 'cd' 命令 的相关文章