fava
fava

Reputation: 153

Test if byte is empty in python

I'd like to test the content of a variable containing a byte in a way like this:

line = []
while True:
    for c in self.ser.read(): # read() from pySerial
        line.append(c)
        if c == binascii.unhexlify('0A').decode('utf8'):
            print("Line: " + line)
            line = []
            break

But this does not work... I'd like also to test, if a byte is empty: In this case

print(self.ser.read())

prints: b'' (with two single quotes)

I do not until now succeed to test this

if self.ser.read() == b''

or what ever always shows a syntax error...

I know, very basic, but I don't get it...

Upvotes: 7

Views: 20959

Answers (2)

fava
fava

Reputation: 153

Thank you for your help. The first part of the question was answerd by @sisanared:

if self.ser.read():

does the test for an empty byte

The second part of the question (the end-of-line with the hex-value 0A) stil doesn't work, but I think it is whise to close this question since the answer to the title is given.

Thank you all

Upvotes: 3

Kian
Kian

Reputation: 1350

If you want to verify the contents of your variable or string which you want to read from pySerial, use the repr() function, something like:

import serial
import repr as reprlib
from binascii import unhexlify
self.ser = serial.Serial(self.port_name, self.baudrate, self.bytesize, self.parity, self.stopbits, self.timeout, self.xonxoff, self.rtscts)
line = []
while 1:
    for c in self.ser.read(): # read() from pySerial
        line.append(c)
        if if c == b'\x0A':
            print("Line: " + line)
            print repr(unhexlify(''.join('0A'.split())).decode('utf8'))
            line = []
            break

Upvotes: 2

Related Questions