How to detect the parity error in PySerial

The PySerial documentation says that if you pass the parity parameters to the __init__(), the “parity checking” feature is enabled. Easy, but it doesn’t work!

The hack is to manually set the right termios flags importing the termios library in addition to the serial lib.

The right termios input flags (c_iflag) are: PARMRK, INPCK and IGNPAR.

Here is an example:

import serial
import termios

ser = serial.Serial (....)

# Get termios settings
iflag, oflag, cflag, lflag, ispeed, ospeed, cc = termios.tcgetattr(ser)

# Enable input parity checking & parity mark with \xff\x00
iflag |= termios.PARMRK | termios.INPCK
iflag &= ~termios.IGNPAR

# Apply termios settings
termios.tcsetattr(ser, termios.TCSANOW, [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])

The parity error will reported as 0xFF, 0x00 prefix.