Executing commands
suggest changePackage exec in standard library is a cross-platform way to launch processes, capture their output and more.
Basic command execution
The simplest usage is:
- create an
exec.Cmdwithexec.Command(exe string, args ...string) - call
cmd.CombinedOutput()to run it and get stdout and stderr together - call
cmd.Output()when you want stdout only (the command's failure still includes stderr in the error)
cmd := exec.Command("go", "version")
out, err := cmd.CombinedOutput()
if err != nil {
log.Fatalf("cmd.CombinedOutput() failed with '%s'\n", err)
}
fmt.Printf("Output:\n%s\n", string(out))
Output:
go version go1.13.4 linux/amd64
More advanced command execution
var stdout, stderr bytes.Buffer
cmd := exec.Command("go", "version")
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Start()
if err != nil {
log.Fatalf("cmd.Start() failed with '%s'\n", err)
}
err = cmd.Wait()
if err != nil {
log.Fatalf("cmd.Wait() failed with '%s'\n", err)
}
out := append(stdout.Bytes(), stderr.Bytes()...)
fmt.Printf("Output:\n%s\n", string(out))
Output:
go version go1.13.4 linux/amd64
This is functionally the same as the above example but we use a more fine-grained control.
We capture stdout and stderr of the process by setting cmd.Stdout and cmd.Stderr to a memory-backed io.Writer.
cmd.Start() starts the command as a new OS process. That process runs concurrently with this one.
We need to call cmd.Wait() to wait for the process to finish. To prevent waiting infinitely, you might want to add a timeout.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents