-2

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}'
David Jones
  • 4,766
  • 3
  • 32
  • 45
azee
  • 27
  • 1
  • 7
  • Parsing a string is done with e.g. strconv.Atoi. And byte slices can be converted to strings directly. This as _absolutely_ _nothing_ to do with the shell. – Volker Jul 04 '19 at 03:37

1 Answers1

1

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 
}
Giulio Micheloni
  • 1,290
  • 11
  • 25
  • it is showing this error: strconv.ParseFloat: parsing "0\n": invalid syntax i alos tried to convert the output first to string and then float insted of directly converting to float . but that also doesnt work.. when i print the out variable (it gives something like this [48 10]. – azee Jul 05 '19 at 03:17
  • You need to parse the string returned by command's stdout and remove invalid chars. In this specific case, try to use `strings.TrimSuffix`. Example: https://play.golang.org/p/U7FFdn08ZHh – Giulio Micheloni Jul 05 '19 at 07:15