我可以使用它out, err := exec.Command("git", "log").Output()来获取命令的输出,该命令将在与可执行位置相同的路径中运行。
out, err := exec.Command("git", "log").Output()
如何指定要在哪个文件夹中运行命令?
exec.Command()返回一个type值*exec.Cmd。Cmd是一个struct并具有一个Dir字段:
exec.Command()
*exec.Cmd
Cmd
Dir
// Dir specifies the working directory of the command. // If Dir is the empty string, Run runs the command in the // calling process's current directory. Dir string
因此,只需在调用之前进行设置Cmd.Output():
Cmd.Output()
cmd:= exec.Command("git", "log") cmd.Dir = "your/intended/working/directory" out, err := cmd.Output()
另请注意,这特定于git命令;git允许您使用该-C标志传递路径,因此您也可以这样操作:
git
-C
out, err := exec.Command("git", "-C", "your/intended/working/directory", "log"). Output()