不能在strconv.ParseFloat问题的参数中使用(type [] byte)作为类型字符串

时间:2017-03-07 21:53:02

标签: go gpio

pi@raspberrypi:~/Desktop/go $ go run shell1.go

结果我得到了:

pi@raspberrypi:~/Desktop/go $ go run shell1.go
# command-line-arguments
./shell1.go:29: undefined: n
./shell1.go:29: cannot use b (type []byte) as type string in argument to strconv.ParseFloat
./shell1.go:32: undefined: n

Go file(shell1.go)代码为:

package main

import (
    //    "net/http"
    //    "github.com/julienschmidt/httprouter"
    "fmt"
    "log"
    "os/exec"
    "strconv"
    "time"
    //"bytes"
    //"encoding/binary"
)
import _ "github.com/go-sql-driver/mysql"
import _ "database/sql"

func main() {
    for {
        time.Sleep(10 * time.Millisecond)
        cmd := exec.Command("gpio.bash")

        b, err := cmd.Output()
        if err != nil {
            log.Fatal(err)
        }
        n, _ = strconv.ParseFloat(b, 10)
        fmt.Println(string(b))
        break
    }

    fmt.Println("Button pressed!!! ", n)

}

gpio.bash)文件的内容只是一个读取gpio的命令

 #!/bin/bash
gpio read 29

1 个答案:

答案 0 :(得分:2)

您正在使用command,这当然可以执行任何操作。

该函数是特意通用的,因为真正的返回类型取决于您执行的内容。因此,当您调用output方法时,会给您一片字节(非常通用!)。这是它的签名:

func (c *Cmd) Output() ([]byte, error)

如果您知道字节将始终是一个字符串,那么您只需要对字符串进行类型转换:

n, _ := strconv.ParseFloat(string(b), 10)