从我的golang程序中的shell程序中解析字节

时间:2019-07-04 03:29:59

标签: go strconv

我正在尝试使用golang(os / exec)调用Shell程序,但是我得到的输出以字节为单位,我需要将其转换为float64,但显示错误?
错误:无法转换为([] 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}'

1 个答案:

答案 0 :(得分: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 
}