event.getKeys only works when a window is open

I’m using PsychoPy v1.84.2 Coder (on a 64-bit Windows 7 PC) to co-ordinate I/O events in an instrumental learning experiment. Since it is unnecessary to present stimuli, I don’t need to create a window, and I’m using Coder’s output window to display messages when a response occurs or a reinforcement is delivered. At the start of the experiment, the user has to make a couple of choices and so I’m wanting the program to detect key presses at this time. However, event.getKeys does not seem to detect any key presses unless a window has been created first. The following code works (i.e. a key press is detected, causing the program to end):

from psychopy import event, visual, core
win = visual.Window()
while True:
    if event.getKeys():
        print "event"
        break

However, if the second line (win = visual.Window()) is removed, key presses are not detected and the program never ends. Is there some way around this?

I have found that the ioHub getPresses() command works in the absence of a window and this is a good alternative to event.getKeys(). I initially struggled to understand how to clear the keyboard buffer prior to the getPresses() statement, because clearEvents() did not work; but then I discovered that clearEvents(device_label=‘keyboard’) does the trick. (In the code below, the first getPresses() command has clear=False so that it leaves a keypress event in the buffer for clearEvents to clear up.)

from psychopy.iohub import launchHubServer

io=launchHubServer()
keyboard = io.devices.keyboard

print "START"
while True:
    if keyboard.getPresses(clear=False):
        print "event"
        break

io.clearEvents(device_label='keyboard')

print "MIDDLE"
while True:
    if keyboard.getPresses():
        print "event"
        break
        
print "END"
1 Like