使用某些参数调用命令有效,但不适用于其他参数,但可以从控制台使用 [英] calling command with some arguments works but not with others but works from console
问题描述
以下代码可以正常工作并输出10个进程的详细信息.
The following code works and outputs details of 10 processes.
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
}
但是,当我尝试使用附加参数"-o cpu"进行相同操作时(例如cmd:= exec.Command(app,"-o cpu","-n 10","-l 2")) .我收到以下错误.
However, when I try the same with an additional argument of "-o cpu" (e.g. cmd := exec.Command(app, "-o cpu", "-n 10", "-l 2")). I get the following error.
exit status 1 invalid argument -o: cpu
/usr/bin/top usage: /usr/bin/top
[-a | -d | -e | -c <mode>]
[-F | -f]
[-h]
[-i <interval>]
[-l <samples>]
[-ncols <columns>]
[-o <key>] [-O <secondaryKey>]
[-R | -r]
[-S]
[-s <delay>]
[-n <nprocs>]
[-stats <key(s)>]
[-pid <processid>]
[-user <username>]
[-U <username>]
[-u]
但是我的控制台中的命令"top -o cpu -n 10 -l 2"可以正常工作.另外,我正在使用OS X 10.9.3.
But the command "top -o cpu -n 10 -l 2" from my console works fine. Also I'm using OS X 10.9.3.
推荐答案
分隔参数.
top -o cpu -n 10 -l 2
不是您正在执行的 .您作为命令参数传递的内容等同于在外壳程序中使用top "-o cpu" "-n 10" "-l 2"
(如果尝试,它将提供完全相同的输出).
top -o cpu -n 10 -l 2
is not what you are executing. What you're passing as arguments to the command is equivalent to using top "-o cpu" "-n 10" "-l 2"
in a shell (which if you try, it will give you the exact same output).
大多数命令都会严格将其解析为3个参数.由于POSIX参数不需要空格,因此top
会分隔-o
作为第一个选项,并将其余部分用作其参数.对于数字参数,这主要是偶然产生的,但对于-o
来说,它查找的是名为" cpu"
的字段,而没有.
Most commands will strictly parse that as 3 arguments. Since POSIX arguments don't require a space, top
splits off the -o
as the first option, and uses the rest as its argument. This works for the numerical arguments mostly by accident, but the for -o
it looks for a field named " cpu"
, which there isn't.
相反,使用
exec.Command(app, "-o", "cpu", "-n", "10", "-l", "2")
这篇关于使用某些参数调用命令有效,但不适用于其他参数,但可以从控制台使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!