Executing Commands with Multiple Arguments
When executing commands in Go, it's important to pay attention to the way arguments are passed to the command. A recent issue encountered by a user was that executing the command "top" with certain arguments worked from the console but failed when using the exec package.
The Problem
The user's code, which successfully executed "top -n 10 -l 2", failed to execute "top -o cpu -n 10 -l 2". The error message provided by the exec package indicated that the "-o cpu" argument was invalid.
The Solution
The issue lies in the way arguments are passed to the command. The command line interpreter on the console automatically separates the arguments, allowing the command to parse them correctly. However, when using the exec package, the arguments must be explicitly separated.
For this particular case, the correct code would be:
cmd := exec.Command(app, "-o", "cpu", "-n", "10", "-l", "2")
By separating the arguments, the exec package can pass them to the command as expected, resolving the error.
The above is the detailed content of Why Does My Go `exec.Command` Fail with Multiple Arguments When the Same Command Works in the Console?. For more information, please follow other related articles on the PHP Chinese website!