Getting SerialException errors with simple Streamlit app communicating with Arduino

This app is deployed locally.

This ultimately will be a bigger project but starting small. The Arduino code is just writing to the serial port a string.

The Python Streamlit code communicates with the Arduino. At this point, I just want to get the reading of the string from the Arduino to work reliably. Here is the code

import streamlit as st
import serial
from serial import SerialException
import traceback

print("----  restarting script -------")

port = '/dev/cu.usbmodem1441201'
baud_rate = 115200

@st.cache_resource
def get_serial_comm():
    try:
        ser = serial.Serial(port, baud_rate)
    except SerialException as e:
        traceback.print_exc()
        raise
    return ser

if st.button('Turn LED On'):
    st.write("LED On")

ser = get_serial_comm()
while True:
    if ser.inWaiting():
        line = ser.readline().decode().rstrip()

When I run the script just using python there are never any SerialException errors. When I run the script with streamlit run some SerialException errors infrequently happen even when nothing happened to prompt it. It always generates a SerialException error when you click the button created by the script.

2024-04-03 21:36:34.967 Uncaught app exception
Traceback (most recent call last):
  File "/Users/hschilli/miniforge3/envs/helen_srep/lib/python3.12/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 542, in _run_script
    exec(code, module.__dict__)
  File "/Users/hschilli/Documents/Hathaway Brown Space Act Agreement/Helen Qiu Project/using Streamlit/minimal_streamlit.py", line 34, in <module>
    line = ser.readline().decode().rstrip()
           ^^^^^^^^^^^^^^
  File "/Users/hschilli/miniforge3/envs/helen_srep/lib/python3.12/site-packages/serial/serialposix.py", line 595, in read
    raise SerialException(
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected or multiple access on port?)

Why does this happen? What am I doing wrong?

Thanks in advance!

I understand that the script gets re-run with each user interaction like clicking the button, but why does that cause an error when reading from the serial port?

Apart from the actual problem, be warned that this app will no longer work after any server deployment. This app will only work locally. Just before you invest any more time…