Run some clean up code before the script is restarted?

I am trying to interface measurement hardware with streamlit. In many cases there is a repetitive measurement performed in a (while) loop. Right now my application has some controls and a run button. When the run button is pressed the actual measurement loop is performed. This works fine. However having some way to interact when the loop is running would be nice too. For example to stop a measurement and do some cleaning up like switching off the output of the power supply etc. As I see it there is currently no way to do that. If I add any control widget to the loop it will restart the script immediatly. Did I overlook something or is something like this on the todo list?