简体   繁体   English

只能串联列表(不是“字节”)以列出

[英]can only concatenate list (not “bytes”) to list

When i try to run this code it give an error: 当我尝试运行此代码时,出现错误:

line = line + device.readBuffer()
TypeError: can only concatenate list (not "bytes") to list 

I googled and found that for python 3, need to add b" " while try to convert bytes to str. 我搜索了一下,发现对于python 3,在尝试将字节转换为str时需要添加b“” After changing this like said this script run for a few seconds then it crashes by giving same error. 像这样说改变之后,该脚本运行了几秒钟,然后由于给出相同的错误而崩溃。

The code: 编码:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import serial
import re
import datetime

class EM408GPS:
    def __init__(self, serialport, baudratespeed):
        self.gpsdevice = serial.Serial(port=serialport, baudrate=baudratespeed, timeout=5)      
        self.init()
    def init(self):       
        if self.isOpen():
            return True      
        return False
    def open(self):
        self.gpsdevice.open()       
    def isOpen(self):
        print("hey")
        return self.gpsdevice.isOpen()  
    def readBuffer(self):
        try:
            data = self.gpsdevice.read(1)
            n = self.gpsdevice.inWaiting()
            if n:
                data = data + self.gpsdevice.read(n)
            return data

        except Exception as e:
            print("Big time read error, what happened: ", e)
            sys.exit(1)

def main():
    device = EM408GPS("COM9", 9600)
    newdata = b""
    line = b""
    while device.isOpen():
        if newdata: 
            line = newdata
            newdata = b""  

        line = line + device.readBuffer()

        if re.search(b"\r\n", line):
            data = line.split(b"\r\n")
            newdata = line.split(b"\r\n")
            #data, newdata = line.split(b"\r\n")

            print ("----" + str(datetime.datetime.now()) + "----")
            print (data)
            print (newdata)

            line = b""
main()

Any help would be appreciated 任何帮助,将不胜感激

if re.search(b"\\r\\n", line) is True, then you split line, which returns type(newdata) = list. 如果re.search(b"\\r\\n", line)为True,则拆分行,返回type(newdata)= list。 Then you assign line = newdata and trying to concat 然后分配line = newdata并尝试连接

line[?] = line[list] + device.readBuffer()[bytes]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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