0

I wanted to do a program which gets data from serial port which start and stop bit will be * and #. Data received will be in *1234567# this form. But it says my 'type' object is not subscriptable. I'm really new to Python i don't know what to do next, can anyone help me to solve this problem?

import serial

ser = serial.Serial(
    port='COM5',\
    baudrate=9600,\
    parity=serial.PARITY_NONE,\
    stopbits=serial.STOPBITS_ONE,\
    bytesize=serial.EIGHTBITS,\
        timeout=0)

MAX_BUF_SIZE = 16
bits = 0

v = memoryview



print("connected to: " + ser.portstr)



while(1):
    for memoryview in ser.read():
        if v[0] == 42:

            if v[-1] == 35:

                print(v[1:-1].tobytes())

        else:
            memoryview = 0
ser.close()

connected to: COM5
Traceback (most recent call last):
  File "C:\Python33\Saves\Receive using buff.py", line 24, in <module>
    if v[0] == 42:
TypeError: 'type' object is not subscriptable
>>> 
4

1 回答 1

1

你正在做的事情过于复杂。我不知道你为什么要使用memoryview。只需这样做:

import serial

ser = serial.Serial(
    port='COM5',
    baudrate=9600,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
    timeout=0)

print("connected to: " + ser.portstr)
for data in ser.read():
    if data[0] == 42 and data[-1] == 35:
           print(data[1:-1].decode())
ser.close()

这不太可能真正按您的意愿工作,但它是您代码的简化。如何实际处理它取决于数据看起来如何更详细。

于 2013-05-03T07:47:21.140 回答