英文:
Execute the 'cd' command for CMD in Go
问题
我想使用Go语言和exec库来进入特定路径“c:\”,并运行一个.exe文件。
当我运行我的Go代码时,它给出了以下错误信息:
exec: "cd:/": 文件不存在
英文:
I want to use Go and the exec library to go to a certain path, "c:", and run a .exe file.
When I run my Go code, it gives me:
> exec: "cd:/": file does not exist
答案1
得分: 11
cd
命令是你的shell的内置命令,无论是bash、cmd.exe、PowerShell还是其他。你不需要执行cd
命令,然后再执行你想要运行的程序。相反,你需要将要运行的Cmd
的Dir
设置为包含该程序的目录:
package main
import (
"fmt"
"log"
"os/exec"
)
func main() {
cmd := exec.Command("program") // 或者是你想要运行的程序
cmd.Dir = "C:/usr/bin" // 或者是它所在的目录
out, err := cmd.Output()
if err != nil {
log.Fatal(err)
} else {
fmt.Printf("%s", out);
}
}
更多信息请参考Cmd文档。或者,你可以在运行程序之前使用os/Chdir来更改工作目录。
英文:
The cd
command is a builtin of your shell, whether bash, cmd.exe, PowerShell, or otherwise. You would not exec a cd
command and then exec the program you want to run. Instead, you want to set the Dir
of the Cmd
you're going to run to the directory containing the program:
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 Cmd documentation for more information. Alternatively, you could use os/Chdir to change the working directory before running the program.
答案2
得分: 3
你可以在Cmd
对象中指定要运行命令的初始工作目录:
cmd.Dir = "C:\\"
有关更多详细信息,请参阅Cmd结构的文档。
英文:
You specify the initial working directory to run the command in the Cmd
object:
cmd.Dir = "C:\\"
See the documentation on the Cmd struct for more details.
答案3
得分: 0
根据命令是否需要在目录的“根”中操作,您可以使用os.Chdir(dir)
来更改Go程序的目录。随后的所有命令和路径都将相对于提供给os.Chdir
的dir
值。
英文:
Depending if the command needs to operate in the "root" of the directory, you can use os.Chdir(dir)
to change Go programs directory. All of the subsequent commands and paths will then be relative to the value of the dir
provided to os.Chdir
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论