Stop python script without causing 3D Slicer to close

Is there a way to stop a python script from running in the Python Console without closing 3D Slicer? I’m running a script to populate data into a table and I want to stop the script and export the data to a csv file. I tried using sys.exit() but this causes the application to close. Any help with this is greatly appreciated!

sys.exit() terminates the current process, so if you run the script in the Slicer process then it will quit Slicer. If you don’t want to quit Slicer then you can put your code in a function and call return to quit from it at any point. You can also allow the user to cancel the processing by hitting a button; for this you just need to call slicer.app.processEvents() time to time in your processing code to allow the application to process GUI events.