Getting serial port to close when exiting experiment early

I’m using code to open the serial port at the start of an experiment to send triggers to a BrainVision EEG system. The port closure code line is at the end of the experiment. If I am piloting or need to exit the experiment early, I have to restart psychopy to get the port to close. Is there a way to run a single line of or add in something to the code so that the can close even if the full script is not run?

The simplest approach would be to use a try … except … finally construct. You can omit the except block if you don’t have any exception you specifically want to catch. Any code in the finally block should run even if the run() function throws an error and crashes.

try:
    run(expInfo, thisExp, win, inputs)
finally:
    closeSerialPort()

I am not 100% if that will catch an interrupt signal (i.e., if you press ctrl+c). To close the serial port in case of an interrupt signal, you could try (this example code was generated by Copilot):

import signal

def signal_handler(signum, frame):
    print("Signal received! Calling interrupt handler...")
    interrupt_handler()

def interrupt_handler():
    print("Cleanup or custom logic executed!")

# Register the signal handler for SIGINT (Ctrl+C)
signal.signal(signal.SIGINT, signal_handler)