```python import serial from serial.tools import list_ports ports = list(list_ports.comports()) i = 1 for p in ports: print(i, ' - ', p.device) i += 1 port = 8 # int(input('Введите номер COM-порта: ')) baudrate = 115200 # int(input('Введите скорость COM-порта: ')) while port > len(ports): print("Такого порта - НЕТ !") port = int(input('Введите номер COM-порта: ')) print(ports[port - 1].device) try: ser = serial.Serial(ports[port - 1].device, baudrate=baudrate) print("Serial connection established.") while True: line = ser.readline().decode().strip() if line: print(line) except serial.SerialException as se: print("Serial port error:", str(se)) except KeyboardInterrupt: pass finally: if ser.is_open: ser.close() print("Serial connection closed.") ```