When working with external system commands in Go, you may encounter the need to capture their output and store it within your program. While the exec and os packages offer various commands for process execution, they typically require file arguments for handling standard input/output. This article addresses a simplified approach for capturing command output as a string.
package main import ( "fmt" "log" "os/exec" ) func main() { out, err := exec.Command("date").Output() if err != nil { log.Fatal(err) } fmt.Printf("The date is %s\n", out) }
In this example, exec.Command("date").Output() is used to run the date command and capture its output in the out variable. The Output() method returns the standard output of the command in the form of a []byte slice, which can be easily converted to a string using string(out).
Alternatively, you can use CombinedOutput() instead of Output(), which returns both standard output and standard error. Additionally, the exec.Command function allows you to set other parameters such as the command's working directory, environment variables, and input.
The above is the detailed content of How to Capture System Command Output as a String in Go?. For more information, please follow other related articles on the PHP Chinese website!