Can't get key press duration for every key - only one value in .csv file

OS (e.g. Win10): MacOS Big Sur 11.1
PsychoPy version (e.g. 1.84.x): 2020.2.1
Standard Standalone? (y/n) If not then what?: Yes
What are you trying to achieve?:
In my experiment, participants must type a word. I want to record the key press duration for each key they press (i.e. how long each key is held down for). I have found documentation using .duration (Keyboard — PsychoPy v2021.2) but I cannot figure out how to implement this into my experiment to get a list of durations for each key press.

What did you try to make it work?:
I have added the following into a code component in my experiment:

Begin routine


Each frame

#keys2 = keyboardCom2.getKeys()
#for key in keys2:
 #   duration.append(key.duration)

keys2 = keyboardCom2.getKeys()
for key in keys2:
    duration = key.duration

As you can see I have tried a few variations of the code above.

End routine

trials_2.addData("holdTimes", duration)

What specifically went wrong when you tried that?:
In the .csv file I get the column called ‘holdTimes’ but in the first row ‘’ is displayed, and the rows below it only show one value. I want a list of durations for every key press, not just one duration overall.

I’m sure I’m doing something slightly wrong with the code but I am struggling to find out what, so any help would be hugely appreciated.

StudentExperiment_v2.psyexp (52.5 KB)

Solution here: Measuring key lift time relative to stimulus onset - #4 by milsandhills