Automatic test of Python serial port

Time:2021-10-18

Installation and usepip install pyserial

Open and exit signals


com = serial.Serial("com15", 115200, timeout=0.5)

def sig_handler(sig, frame):
    com.close()
    exit(0)

signal.signal(signal.SIGTERM, sig_handler)
signal.signal(signal.SIGINT, sig_handler)

try:
    com.open()
except:
    com.close()
    com.open()

Read one line of output

    try:
        readline = str(com.readline(), encoding = "utf8")
    except:
        continue

Send the specified command when reading the specified information

    try:
        if re.findall(r'xxx readline, flags=0):
            com.write(bytes("\r\nreboot\r\n", encoding = "utf8"))
    except:
        print("some errr....")