gpt4 book ai didi

Python IndexError : list index out of range. 无法按索引访问

转载 作者:太空宇宙 更新时间:2023-11-03 11:44:14 25 4
gpt4 key购买 nike

我正在使用 pySerial 读取 TTL 字节流。读取两个字节:

CheckSumByte = [ b for b in ser.read(2)]
print( CheckSumByte)
print( type(CheckSumByte))
print( str(len(CheckSumByte)))
print( CheckSumByte[0])

输出:

[202, 87]
<class 'list'>
2
IndexError: list index out of range

我无法通过索引(0 或 1)访问 CheckSumByte 的任何元素。怎么了?

这是我的代码:

while(ReadBufferCount < 1000):
time.sleep(0.00002)
InputBuffer = ser.inWaiting()
if (InputBuffer > 0):
FirstByte = ser.read(1)
if ord(FirstByte) == 0xFA:
while ser.inWaiting() < 21: pass
IndexByte = ser.read(1)
SpeedByte = [ b for b in ser.read(2)]
DataByte0 = [ b for b in ser.read(4)]
DataByte1 = [ b for b in ser.read(4)]
DataByte2 = [ b for b in ser.read(4)]
DataByte3 = [ b for b in ser.read(4)]
CheckSumByte = [ b for b in ser.read(2)]
print( CheckSumByte[0]) #Out of Range??`
Traceback (most recent call last):

File "<ipython-input-6-5233b0a578b1>", line 1, in <module>
runfile('C:/Users/Blair/Documents/Python/Neato XV-11 Lidar/Serial9.py', wdir='C:/Users/Blair/Documents/Python/Neato XV-11 Lidar')

File "C:\Program Files (x86)\WinPython-32bit-3.4.3.3\python-3.4.3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 682, in runfile
execfile(filename, namespace)

File "C:\Program Files (x86)\WinPython-32bit-3.4.3.3\python-3.4.3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)

File "C:/Users/Blair/Documents/Python/Neato XV-11 Lidar/Serial9.py", line 88, in <module>
print( CheckSumByte[0]) #Out of Range??

IndexError: list index out of range

肯尼:谢谢。两个字节更简单:

    CheckSumByte.append(ser.read(1))
CheckSumByte.append(ser.read(1))

工作正常,但很笨拙。这些项目是类型字节。如何使用列表理解将项目添加到列表中?我想避免附加功能,因为它很慢。

我注意到当 CheckSumByte 的项目是整数时它不起作用。 Python 3 列表理解是否需要特殊格式才能将字节添加为字节(不转换为整数)?

最佳答案

根据您最近的评论,您将 ser 构造为:

ser = serial.Serial(
port=PortName, baudrate=115200, parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS,
timeout=0)

根据documentation这意味着 ser非阻塞(尽管你断言它是阻塞的!)。

因为它处于非阻塞模式,所以绝对没有理由期望 ser.read(n) 返回恰好 n 字节。相反,如果你想读取 n 字节,你应该:

  • 在构造函数中将 ser 构造为阻塞(使用 timeout=None);或
  • 循环同时监控实际读取的字节数(就像读取网络套接字时一样)

例如,后者意味着如果您希望读取 n 个字节,您需要执行以下操作:

def read_exactly(ser, n):
bytes = b""

while len(bytes) < n:
bytes += ser.read(n - len(bytes))

return bytes

在您的特定情况下,您似乎正在监视输入缓冲区以确保有足够的数据用于后续读取。但是这种监控只是在一些的时间发生,而不是所有的时间。因此,当 FirstByte != 0xFA 时,您可能会耗尽读取缓冲区,除非您采用上面给出的方法之一。

关于Python IndexError : list index out of range. 无法按索引访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43024879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com