psychopy.org | Reference | Downloads | Github

Pressing ESC key at any moment to end the experiment

Hello,

I’ve build an experiment which goes through many phases and loops. However, I would like to be able to press the “ESC” key at any given moment while the experiment is running in order to close the window and end the experiment.

I’m aware that I could use this chunk of code:

while True:
        keys = event.getKeys()
        if keys:
            if keys[0] == 'Esc':
                win.close()
                core.quit()

However, I would have to add this bit of code it to every loop and routine, which may be problematic in some cases. What I’m looking for is an easier way to accomplish this. For example, I’m hopping for a “global option” that I can setup at the beginning of the experiment? If not, which would be the best way to proceed?

Thank you for your inputs.

1 Like

Hi, the code you posted above would actually halt the entire experiment until escape is pressed. I presume this is not actually what you want? You could create two functions like this:

def get_keypress():
    keys = event.getKeys()
    if keys:
        return keys[0]
    else:
        return None

def shutdown():
    win.close()
    core.quit()

In your loops and routines, you could then simply insert a code snippet like this:

key = get_keypress()
if key is None:
    # No response
    ...
elif key == 'Esc'
    shutdown()
else:
    # Save response to logfile?
    ...

You could also do the Esc checking inside the get_keypress() function, or even combine both functions into a single one:

def get_keypress():
    keys = event.getKeys()
    if keys and keys[0] == 'Esc':
        win.close()
        core.quit()
    elif keys:
        return keys[0]
    else:
        return None

# Loop here:
key = get_keypress()
if key is None:
    # No response
    ...
else:
    # Save response to logfile?
    ...

but whether this makes sense or not really depends on your specific requirements and experimental paradigm etc.

1 Like