doupu1949 2014-06-26 10:02
浏览 24
已采纳

使用某些参数调用命令有效,但不适用于其他参数,但可以从控制台使用

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条回答 默认 最新

  • dongzhabo2796 2014-06-26 11:47
    关注

    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")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来