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文件(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
最佳答案
您正在使用 command在这里,它当然可以执行任何事情。
该函数特意是通用的,因为真正的返回类型因您执行的内容而异。因此,当您调用 output方法,您将获得一段字节(非常通用!)。这是它的签名:
func (c *Cmd) Output() ([]byte, error)
如果你知道字节总是一个字符串,那么你只需要做一个字符串类型转换:
n, _ := strconv.ParseFloat(string(b), 10)
关于go - 不能在 strconv.ParseFloat 问题的参数中使用 (type []byte) 作为类型字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42659045/