[英]How to add bytes to bytearray in Python 3.7?
I am new the Python 3.7 and I am trying to read bytes from a serial port using the following code.我是 Python 3.7 的新手,我正在尝试使用以下代码从串口读取字节。 I am using
pySerial
module and the read() function returns bytes
.我正在使用
pySerial
模块并且read()函数返回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
I receive the following error:我收到以下错误:
TypeError: an integer is required
类型错误:需要一个整数
Some idea how to solve?一些想法如何解决?
packet_bytes += bytearray(current_bytes)
I recently had this problem myself and this is what worked for me.我自己最近遇到了这个问题,这对我有用。 Instead of instantiating a bytearray, I just initialized my buffer as a byte object:
我没有实例化字节数组,而是将缓冲区初始化为字节对象:
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'\015': ENTER
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.