使用某些参数调用命令但不能与其他参数一起使用,但可以从控

时间:2014-06-26 10:02:22

标签: go

以下代码可以处理并输出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。

1 个答案:

答案 0 :(得分:4)

分开你的论点。

top -o cpu -n 10 -l 2 您正在执行的内容。你作为命令的参数传递的内容相当于在shell中使用top "-o cpu" "-n 10" "-l 2"(如果你尝试,它会给你完全相同的输出)。

大多数命令将严格解析为3个参数。由于POSIX参数不需要空格,top-o作为第一个选项拆分,并使用其余参数作为参数。这主要用于数字参数,但是-o for " cpu"查找名为exec.Command(app, "-o", "cpu", "-n", "10", "-l", "2") 的字段,但没有。{/ p>

相反,请使用

{{1}}