| Reference | Downloads | Github

Write a list of key presses to output

OS (e.g. Win10): macOS Mojave
PsychoPy version (e.g. 1.84.x): 3.0.1
Standard Standalone? yes

What are you trying to achieve?:
I’m designing a block design fMRI task that should not advance with the trigger (after the initial one), but I would like to record all triggers and onset times. For now, I’m testing with ‘5’ on the keyboard and would like to save all key presses (i.e., all triggers and button responses) within a single routine and write them to csv.

What did you try to make it work?:
In the builder I’ve selected “Store all keys” for the “trigger” keyboard component, and I have set an fmriClock() to begin after the initial trigger. I have tried using the csv.writer within a code component to write the list of key presses—directly from the TrialHandler list trigger.keys, from theseKeys, and from an empty list that should be populated with key presses.

I have tried adding an empty list at the beginning of the experiment and adding each element to the list in a loop, then writing to csv:

Begin Experiment

import csv

timing_filename = '%s_timing_file.csv'%(expInfo['participant'])
onset_file = open(timing_filename, 'w')
onswriter = csv.writer(onset_file, dialect='excel')

trigger_keys = []

End Routine

for key in trigger.keys:


Although I’m passing a list of key presses, it usually returns a fraction of the 5’s in the output (sometimes just one).

It behaves similarly if I use writer.writerows() on trigger.keys() directly.


I have also tried using writerow on each element in the list:

for i in range(trigger.keys):

But I get the following error: TypeError: ‘list’ object cannot be interpreted as an integer

None of these approaches write the correct list of keys. Although I’m requesting that all keypresses be saved, it behaves as though trigger.keys is an empty list.

Finally, I’m not sure how to call the custom fmriClock() when a key is pressed to output the onset time. I would appreciate any advice on this.

HI @andreac, have you tried using the experiment handler to write the data? You can just use the following in your code component, in the ‘end routine’ tab:

thisExp.addData("MyList", trigger.keys)

This will add a list of keys pressed to a column called “myList” in your datafile.