简体   繁体   中英

How to find the byte data in pyserial readline in Python 3.x

How to find the substring in serial byte data that is newline terminated. I just want to extract the data from the uart stream.

Not able to find byte data in Pyserial line.

I can able to find imei the first line but the second line it's not able to find in several ways I tried?

EDIT: It's a typo no escape sequence.

Output in my UART stream:

b'\xfeimei_1234567777777\n'
b'ccid_123123324234234234324\n'

Any help very appreciated.

Minimal code example:

IMEI=b'imei_'

CCID=b'ccid_'
ccid = b'ccid_123123324234234234324\n'
XFIND_CCID=b'ccid_12'
OCCID=b'12'

#Here open the serial connection
run = True
while run:
  data=device.readline()
  print(data)

  #It works for this well without any issue.
  if data.find(IMEI) == 1:
      v_imei = data
      print(imei)

  #None of the method works
  #Method 1
  if data.find(CCID) == 1:
      ccid = data
      print(ccid)

  #Method 2
  if data.find(ccid) == 1:
      v_ccid = data
      print("Hurray we found the CCID %s" % v_ccid)

  #Method 3
  if data.find(OCCID) == 1:
      v_ccid = data
      print("OCCID we found the CCID %s" % v_ccid)


  #Method 4
  if data.find(XFIND_CCID) == 1:
      print("XX Hurray we found the CCID")

  if data == "end"
      run = False

The short answer to your question is that bytes.find , like str.find , returns the starting index of the first matching character it finds.

The first comparison works because you have \\xfe at index 0, placing imei indeed at index 1.

The remaining comparisons don't work because ccid_ is at index 0, not index 1 in the second line.

If you want a bool indicating whether one bytes appears in another, and don't really care about the index, use the in operator instead, eg:

 if CCID in data:

If you really do care about the index, you can check that find returns non-negative, since it returns -1 if the item is not found:

if data.find(CCID) >= 0:

Your final option is to use exception handling. This is only really a good way if you want to work with the assumption that the CCID must be in your data and anything else is really abnormal. The index method is like find , except it raises an error instead of returning -1 :

try:
    i = data.index(ccid)
    # ok, index found
except IndexError:
    # not ok

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM