执行命令不获取结果

直接调用run()

  1. package main
  2. import (
  3. "fmt"
  4. "os/exec"
  5. )
  6. func main() {
  7. //新建文件1.txt
  8. cmd := exec.Command("cmd", "/C", "echo", "111111", ">", "1.txt").Run()
  9. fmt.Println(cmd)
  10. }

image.png

  1. package main
  2. import (
  3. "fmt"
  4. "os/exec"
  5. )
  6. func main() {
  7. cmd, _ := exec.Command("cmd", "/C", "echo", "123", ">", "123.txt").CombinedOutput()
  8. fmt.Println(string(cmd))
  9. }

image.png
如果是Linux就简单了,不用cmd /C。

执行命令并获取结果

使用CombinedOutput函数。

  1. package main
  2. import (
  3. "fmt"
  4. "os/exec"
  5. )
  6. func main() {
  7. //新建文件1.txt
  8. cmd, _ := exec.Command("cmd", "/C", "echo", "222222").CombinedOutput()
  9. fmt.Println(string(cmd))
  10. }

image.png