英文:
calling command with some arguments works but not with others but works from console
问题
以下是代码的翻译结果:
以下代码可以正常工作并输出10个进程的详细信息。
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")
),我会得到以下错误信息:
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操作系统。
英文:
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
}
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]
But the command "top -o cpu -n 10 -l 2" from my console works fine. Also I'm using OS X 10.9.3.
答案1
得分: 6
将你的参数分开。
top -o cpu -n 10 -l 2
不是你正在执行的命令。你传递给命令的参数等同于在shell中使用 top "-o cpu" "-n 10" "-l 2"
(如果你尝试,会得到完全相同的输出)。
大多数命令会严格解析这3个参数。由于POSIX参数不需要空格,top
将 -o
作为第一个选项分离出来,并将剩下的部分作为它的参数。这在大多数情况下是偶然的,但对于 -o
来说,它会寻找一个名为 " cpu"
的字段,而实际上并不存在。
相反,使用以下方式:
exec.Command(app, "-o", "cpu", "-n", "10", "-l", "2")
英文:
Separate your arguments.
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).
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.
Instead, use
exec.Command(app, "-o", "cpu", "-n", "10", "-l", "2")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论