Python索引器错误:列表索引超出范围。无法按索引访问

2024-06-26 18:08:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

输出:

^{pr2}$

我无法通过索引(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))

工作正常,但很尴尬。这些项是字节类型。如何使用列表理解将项目添加到列表中?我想避免使用append函数,因为它很慢。在

当整数项的sum不起作用时,请注意。Python3列表理解是否需要特殊格式将字节作为字节添加(而不是转换为整数)?在


Tags: ofinpyforread字节lineusers
2条回答

顿科波塔姆斯-你找到答案了。我把封条弄混了。我设置timeout=0以尝试其他设置。你说得对,ser可以读取零字节。我忘了把它设回timeout=None。现在总是读取一些字节。不再有索引器。非常感谢你。在

根据您最近的评论,您将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字节,则需要执行以下操作:

^{pr2}$

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

相关问题 更多 >