i am trying to call a shell program using golang (os/exec) but the output i am getting is in bytes and i need to convert it into float64 but it is showing error?
error: cannot convert out (type []byte) to type 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 is:
top -b n 1 | egrep -w 'apache2|mysqld|php' | awk '{cpu += $9}END{print cpu/NR}'
Use bytes.Buffer
and strconv.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
}