如何在 Python 3.7 中向 bytearray 添加字节?
How to add bytes to bytearray in Python 3.7?
我是 Python 3.7 的新手,我正在尝试使用以下代码从串口读取字节。我正在使用 pySerial
模块和 read() 函数 returns bytes
。
self.uart = serial.Serial()
self.uart.port = '/dev/tty/USB0'
self.uart.baudrate = 115200
self.uart.open()
# buffer for received bytes
packet_bytes = bytearray()
# read and process data from serial port
while True:
# read single byte from serial port
current_bytes = self._uart.read()
if current_bytes is B'$':
self.process_packet(packet_bytes)
packet_bytes = bytearray()
else:
packet_bytes.append(current_bytes) <- Error occurs here
我收到以下错误:
TypeError: an integer is required
一些想法如何解决?
packet_bytes += bytearray(current_bytes)
我自己最近也遇到了这个问题,这对我有用。我没有实例化字节数组,而是将缓冲区初始化为字节对象:
buf = b"" #Initialize byte object
poll = uselect.poll()
poll.register(uart, uselect.POLLIN)
while True:
ch = uart.read(1) if poll.poll() else None
if ch == b'x':
buf += ch #append the byte character to the buffer
if ch == b'y':
buf = buf[:-1] #remove the last byte character from the buffer
if ch == b'5': ENTER
break
我是 Python 3.7 的新手,我正在尝试使用以下代码从串口读取字节。我正在使用 pySerial
模块和 read() 函数 returns bytes
。
self.uart = serial.Serial()
self.uart.port = '/dev/tty/USB0'
self.uart.baudrate = 115200
self.uart.open()
# buffer for received bytes
packet_bytes = bytearray()
# read and process data from serial port
while True:
# read single byte from serial port
current_bytes = self._uart.read()
if current_bytes is B'$':
self.process_packet(packet_bytes)
packet_bytes = bytearray()
else:
packet_bytes.append(current_bytes) <- Error occurs here
我收到以下错误:
TypeError: an integer is required
一些想法如何解决?
packet_bytes += bytearray(current_bytes)
我自己最近也遇到了这个问题,这对我有用。我没有实例化字节数组,而是将缓冲区初始化为字节对象:
buf = b"" #Initialize byte object
poll = uselect.poll()
poll.register(uart, uselect.POLLIN)
while True:
ch = uart.read(1) if poll.poll() else None
if ch == b'x':
buf += ch #append the byte character to the buffer
if ch == b'y':
buf = buf[:-1] #remove the last byte character from the buffer
if ch == b'5': ENTER
break