os/exec包帮助你在 Go 中执行终端命令。


执行系统命令非常简单。Cmd 保存您的外部命令。


所以在 linux 中假设你想运行“echo hello”命令,你会写下面的代码。


cmdStruct := exec.Command("echo","hello")    

out,err := cmdStruct.Output()

if err != nil {

    fmt.Println(err)

}

fmt.Println(string(out))

这是最基本的方法之一。但是,在 Windows 中,您需要将“echo hello”作为参数传递给命令提示符或 Powershell。


    cmdStruct:= exec.Command("cmd.exe","/c","echo","hello")

为了简化单个切片中的传递参数,


args:= strings.Split("/c echo hello there how are you"," ")

cmdStruct:= exec.Command("cmd.exe",args...)

查看此答案以获得更好的理解和此代码的增强版本。


对于 cd,您可以使用os.Chdir()和os.Getwd()分别更改和查看您的工作目录。但是如果你需要你的命令在特定目录中执行,你可以设置Dir你的命令,即


cmdStruct.Dir = "path/to/directory"

或者


cmdStruct.Dir = filepath.Join("path","to","directory")