-2

我正在尝试使用 golang (os/exec) 调用 shell 程序,但我得到的输出是以字节为单位的,我需要将其转换为 float64,但它显示错误?
错误:无法将 (type []byte) 转换为 float64 类型

     func Cpu_usage_data() (cpu_predict float64, err error) {
     out,err1 := exec.Command("/bin/sh","data_cpu.sh").Output()
 if err1 != nil {
      fmt.Println(err1.Error())
    }
  return float64(out), err1
    } 

data_cpu.sh 是:

  top -b n 1 | egrep -w 'apache2|mysqld|php' | awk '{cpu += $9}END{print cpu/NR}'
4

1 回答 1

1

使用bytes.Bufferstrconv.ParseFloat

func Cpu_usage_data() (cpu_predict float64, err error) {
    cmd := exec.Command("/bin/sh", "data_cpu.sh")
    var out bytes.Buffer
    cmd.Stdout = &out
    err = cmd.Run()
    if err != nil {
        fmt.Println(err.Error())
    }
    cpu_predict, err = strconv.ParseFloat(out.String(), 64)
    if err != nil {
        fmt.Println(err.Error())
    }
    return 
}
于 2019-07-04T10:15:51.893 回答