Golang中如何执行cmd命令并打印输出结果
Golang中如何执行cmd命令并打印输出结果 我想执行一个返回 Node.js 版本或其他任何 cmd 命令的 cmd 或 shell 命令,该如何实现?我有以下代码:
import (
"fmt"
"os"
"os/exec"
)
func main(){
output, err := exec.Command("cmd", "node -v").CombinedOutput()
if err != nil {
os.Stderr.WriteString(err.Error())
}
fmt.Println(string(output))
}
我期望的输出是:“v14.12.0”
实际得到的输出是:“Microsoft Windows [Versi�n 10.0.19042.928]”
更多关于Golang中如何执行cmd命令并打印输出结果的实战教程也可以访问 https://www.itying.com/category-94-b0.html
3 回复
我认为你需要给 cmd.exe 加上 /c 开关:
output, err := exec.Command("cmd", "/c", "node -v").CombinedOutput()
更多关于Golang中如何执行cmd命令并打印输出结果的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
cmd := "node -v"
output, _ := exec.Command("bash", "-c", cmd).Output()
并且你可以在 cmd 中放置长的、甚至是多命令的命令,例如:
cmd := fmt.Sprintf("cd %s; tar czf %s.tgz *.log; tar tvf %s.tgz", path, taskId, taskId)
在Windows系统中,exec.Command的第一个参数是程序名,后续参数需要分开传递。你的代码将"node -v"作为单个参数传递给了cmd,这导致cmd执行了错误的命令。
以下是修正后的代码:
package main
import (
"fmt"
"os"
"os/exec"
)
func main() {
// Windows系统:使用cmd /c执行命令
cmd := exec.Command("cmd", "/c", "node -v")
output, err := cmd.CombinedOutput()
if err != nil {
os.Stderr.WriteString(err.Error())
return
}
fmt.Print(string(output))
}
或者使用更通用的方式,直接调用node程序:
package main
import (
"fmt"
"os"
"os/exec"
)
func main() {
// 直接调用node程序
cmd := exec.Command("node", "-v")
output, err := cmd.CombinedOutput()
if err != nil {
os.Stderr.WriteString(err.Error())
return
}
fmt.Print(string(output))
}
对于其他shell命令,可以使用以下模式:
package main
import (
"fmt"
"os"
"os/exec"
)
func main() {
// 执行dir命令(Windows)
cmd := exec.Command("cmd", "/c", "dir")
output, err := cmd.CombinedOutput()
if err != nil {
os.Stderr.WriteString(err.Error())
return
}
fmt.Print(string(output))
}
在Linux/macOS系统中,使用bash:
package main
import (
"fmt"
"os"
"os/exec"
)
func main() {
// Linux/macOS系统
cmd := exec.Command("bash", "-c", "node -v")
output, err := cmd.CombinedOutput()
if err != nil {
os.Stderr.WriteString(err.Error())
return
}
fmt.Print(string(output))
}
如果需要实时输出(逐行处理),可以使用以下方式:
package main
import (
"bufio"
"fmt"
"io"
"os"
"os/exec"
)
func main() {
cmd := exec.Command("node", "-v")
stdout, err := cmd.StdoutPipe()
if err != nil {
os.Stderr.WriteString(err.Error())
return
}
stderr, err := cmd.StderrPipe()
if err != nil {
os.Stderr.WriteString(err.Error())
return
}
if err := cmd.Start(); err != nil {
os.Stderr.WriteString(err.Error())
return
}
// 读取标准输出
go func() {
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
}()
// 读取标准错误
go func() {
scanner := bufio.NewScanner(stderr)
for scanner.Scan() {
fmt.Fprintln(os.Stderr, scanner.Text())
}
}()
cmd.Wait()
}

