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

报告相同问题?

悬赏问题

  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序