Using Command Line Arguments with Go
This Go code successfully retrieves details of 10 processes using the "top" command with specific arguments:
package main import ( "os/exec" ) func main() { print(top()) } func top() string { app := "/usr/bin/top" cmd := exec.Command(app, "-n", "10", "-l", "2") out, err := cmd.CombinedOutput() if err != nil { return err.Error() + " " + string(out) } value := string(out) return value }
However, an additional "-o cpu" argument causes an error:
cmd := exec.Command(app, "-o", "cpu", "-n", "10", "-l", "2")
In the console, the command "top -o cpu -n 10 -l 2" works as intended. The issue lies in the way the "-o" argument is being passed to the "top" command.
To resolve this, it's necessary to separate the arguments explicitly like:
cmd := exec.Command(app, "-o", "cpu", "-n", "10", "-l", "2")
This ensures that the arguments are passed correctly to the command, allowing it to execute properly.
The above is the detailed content of Why Does Adding '-o cpu' to My Go `exec.Command` for `top` Cause an Error, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!