参数为%和的exec命令

时间:2019-05-16 07:24:29

标签: go

我需要在Linux上运行以下命令并使用golang获取输出。

/bin/ps o pid,%cpu,%mem -p 14806

命令运行正常,并产生如下结果:

  PID %CPU %MEM
14806  0.8  6.0

但无法通过golang代码运行

package main

import (
    "fmt"
    "log"
    "os/exec"
)

func main() {

    cmd := exec.Command("ps", "o pid,%cpu,%mem -p 14806")
    fmt.Printf("Path: %q, args[1]: %q\n", cmd.Path, cmd.Args[1])

    out, err := exec.Command("ps", "o pid,%cpu,%mem -p 14806").Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("The date is %s\n", out)
}


输出

Path: "/bin/ps", args[1]: "o pid,%cpu,%mem -p 14806"
2019/05/16 07:23:17 exit status 1
exit status 1

1 个答案:

答案 0 :(得分:0)

感谢@Volker

以下代码有效

package main

import (
    "fmt"
    "log"
    "os/exec"
)

func main() {

    cmd := exec.Command("ps", "--no-headers", "o", "pid,%cpu,%mem", "-p", "14806")
    fmt.Printf("Path: %q, args[1]: %q\n", cmd.Path, cmd.Args[1])

    out, err := exec.Command("ps", "--no-headers", "o", "pid,%cpu,%mem", "-p", "14806").Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%s\n", out)
}