PySerial minimal request-reply example

This example sends the M119 (print endstop status) command to an attached 3D printer and prints the response in a loop

#!/usr/bin/env python3
import serial
ser = serial.Serial("/dev/ttyACM0")

try:
    while True:
        ser.write(b"M119\n")
        response = ser.read_until(b"ok\n")
        print(response.decode("utf-8"))
finally:
    ser.close()

Example output (in a loop):

Reporting endstop status
x_max: open
y_max: TRIGGERED
z_max: TRIGGERED
ok