Invoking External Commands in Go
In Go, accessing external commands and ensuring their completion before proceeding with subsequent operations is essential. To address this need, the exec package provides a robust mechanism.
Command Execution with Waiting
The exec.Command function allows you to create a new command with specified arguments. To run the command and wait for its completion before executing the next statement, use the Run method.
<code class="go">cmd := exec.Command("yourcommand", "some", "args") if err := cmd.Run(); err != nil { fmt.Println("Error:", err) }</code>
Retrieving Command Output
If you only require the output of the external command, you can utilize the Output method instead of Run. This method returns a byte array containing the command's standard output.
<code class="go">cmd := exec.Command("yourcommand", "some", "args") output, err := cmd.Output() if err != nil { fmt.Println("Error:", err) } else { fmt.Println("Output:", string(output)) }</code>
The above is the detailed content of How do you execute external commands and retrieve their output in Go?. For more information, please follow other related articles on the PHP Chinese website!