Calling an external command in Go

后端 未结 2 974
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-20 21:22

How can I call an external command in GO? I need to call an external program and wait for it to finish execution. before the next statement is executed.

相关标签:
2条回答
  • 2021-01-20 21:43
    package main
    
    import (
      "fmt"
      "os/exec"
      "log"
    )
    
    func main() {
      cmd := exec.Command("ls", "-ltr")
      out, err := cmd.CombinedOutput()
      if err != nil {
        log.Fatal(err)
      }
      fmt.Printf("%s\n", out)
    }
    

    Try online

    0 讨论(0)
  • 2021-01-20 22:01

    You need to use the exec package : start a command using Command and use Run to wait for completion.

    cmd := exec.Command("yourcommand", "some", "args")
    if err := cmd.Run(); err != nil { 
        fmt.Println("Error: ", err)
    }   
    

    If you just want to read the result, you may use Output instead of Run.

    0 讨论(0)
提交回复
热议问题