简体   繁体   中英

a byte like object is required not string in python 3 parsegps(str)

am trying to write a code that well read data from my serial UART and parse the NMEA gps sentence by using pynmea2 module i was running this code in python 2 and it worked like magic ,when i tried to run it with python3 a type error rise am using python idle to write the code in my raspberry pi 3 and all the hardware between neo 6m gps and the raspberry are fine my code is blow `

import serial
import pynmea2

def parseGPS(str):

    if str.find('GGA') > 0:
        msg = pynmea2.parse(str)
        #print "Timestamp: %s -- Lat: %s %s -- Lon: %s %s -- Altitude: %s %s" % (msg.timestamp,msg.lat,msg.lat_dir,msg.lon,msg.lon_dir,msg.altitude,msg.altitude_units)

serialPort = serial.Serial("/dev/ttyS0", 9600, timeout=0.5)

while True:
    str = serialPort.readline()
    parseGPS(str)

`

and i get this Messag

 "if str.find('GGA').0:
    TypeError:'a bytes-like object is required, not 'str' "

In Python 3.x, text is always Unicode and is represented by the str type, and binary data is represented by the bytes type. serial.readline() in fact returns binary data, and therefor in bytes type. This is different from Python 2.x.

You can convert the encoded bytes data into str with:

str = serailPort.readline().decode()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM