Keydown time

1,099 views
Skip to first unread message

Will

unread,
Jan 13, 2010, 10:18:02 AM1/13/10
to psychopy-users
Hi,

Is there a simple way to measure the time for which a key is held
down? I know how to use event.getKeys() to record the time of a
keypress, but I'm interested in recording the interval between key
down and key up, and can't work out what to do.

If it's any easier, I'd be just as interested in recording the time
that a mouse button is pressed.

I unfortunately don't have a specialized button box etc, so I
appreciate that any timing of keypresses etc will be error-prone.

Thanks for your help,

Will

Dave Britton

unread,
Jan 18, 2010, 9:50:34 AM1/18/10
to psychop...@googlegroups.com
Will,
Psychopy generally uses pyglet for processing keyboard events, so if
your installation is standard, then you have pyglet available so you can
use the pyglet keyStateHandler function:

http://www.pyglet.org/doc/api/pyglet.window.key.KeyStateHandler-class.html

the key state handler lets you know when a key is released.
pyglet docs show this example:
====================
Simple handler that tracks the state of keys on the keyboard. If a key
is pressed then this handler holds a True value for it.

For example:

>>> win = window.Window
>>> keyboard = key.KeyStateHandler()
>>> win.push_handlers(keyboard)

# Hold down the "up" arrow...

>>> keyboard[key.UP]
True
>>> keyboard[key.DOWN]
False
===================
The pyglet window.Window object will be the same as the psychopy Window,
I believe. You would want to block all other processing activity
probably, while you poll the state of the keyboard, to be sure you have
the most accurate time:

# wait for the key (up-arrow in this example) to be pressed:
# (pyglet has constants defined for all the keys)
while not keyboard(key.UP):
... pass
# immediately after key is pressed:
t1=time() # or use psychopy Clock
while keyboard(key.UP):
... pass # stop everything until up-arrow key is released
t2=time()
elapsedtime=t2-t1

If you need to do other stuff while the key is being held, you will have
to write a more complex handler that attaches a callback to the keyup
event to capture the time when the pyglet event loop notices the key is
released. (No longer a simple way.)

-Dave

ShoinExp

unread,
Apr 16, 2013, 10:01:09 AM4/16/13
to psychop...@googlegroups.com
Hi Dave,
    This is an old post, but I'm trying to do the same thing.  I'm not a coder at all, so I'm cutting, pasting and praying.  When I added your code to my experiment (which at the moment is just a single trial with a single keyboard-event so that I can play around with getting your code working), I got the following error:

  win = window.Window
NameError: name 'window' is not defined

    Undoubtedly I'm not taking something obvious into account, any thoughts?
    Thanks,
    Mark

Andre Gouws

unread,
Apr 16, 2013, 10:28:42 AM4/16/13
to psychop...@googlegroups.com
should probably be "visual.Window" not "window.Window"


--
You received this message because you are subscribed to the Google Groups "psychopy-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to psychopy-user...@googlegroups.com.
To post to this group, send email to psychop...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msg/psychopy-users/-/Qzc4_RqAxZoJ.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

ShoinExp

unread,
Apr 16, 2013, 10:13:07 PM4/16/13
to psychop...@googlegroups.com
Hi Andre,
    Thanks for that.  I changed to visual.Window and that solved that problem, but now I have a new error:

win.push_handlers(keyboard)
AttributeError: class Window has no attribute 'push_handlers'

    Any thoughts on that one?
    Thanks,
    Mark

Michael MacAskill

unread,
Apr 16, 2013, 11:32:48 PM4/16/13
to psychop...@googlegroups.com

This is a class (i.e. the definition of what a Window is and what it does):
visual.Window

This is a function that returns an actual instance of a class that you can actually do things with:
visual.Window()

You want the second one.

Mike


On 17 Apr, 2013, at 14:13, ShoinExp <mark.a....@gmail.com> wrote:

> Hi Andre,
> Thanks for that. I changed to visual.Window and that solved that problem, but now I have a new error:
>
> win.push_handlers(keyboard)
> AttributeError: class Window has no attribute 'push_handlers'
>
> Any thoughts on that one?
> Thanks,
> Mark
>
> On Tuesday, April 16, 2013 11:28:42 PM UTC+9, Andre Gouws wrote:
> should probably be "visual.Window" not "window.Window"
>
>
> On Tue, Apr 16, 2013 at 3:01 PM, ShoinExp <mark.a....@gmail.com> wrote:
> Hi Dave,
> This is an old post, but I'm trying to do the same thing. I'm not a coder at all, so I'm cutting, pasting and praying. When I added your code to my experiment (which at the moment is just a single trial with a single keyboard-event so that I can play around with getting your code working), I got the following error:
>
> win = window.Window
> NameError: name 'window' is not defined

--
Michael R. MacAskill, PhD michael....@nzbri.org
Research Director,
New Zealand Brain Research Institute

66 Stewart St http://www.nzbri.org/macaskill
Christchurch 8011 Ph: +64 3 3786 072
NEW ZEALAND Fax: +64 3 3786 080










Jonathan Peirce

unread,
Apr 17, 2013, 4:39:41 AM4/17/13
to psychop...@googlegroups.com
Actually, I think the code Mark is referring to is for the pyglet
window, not the psychopy window. That's stored by psychopy as
Window.winHandle. So you would do::

from psychopy import visual
win = visual.Window(......)
.....
win.winHandle.push_handlers(keyboard)

Jon

On 17/04/2013 04:32, Michael MacAskill wrote:
> This is a class (i.e. the definition of what a Window is and what it does):
> visual.Window
>
> This is a function that returns an actual instance of a class that you can actually do things with:
> visual.Window()
>
> You want the second one.
>
> Mike
>
>
> On 17 Apr, 2013, at 14:13, ShoinExp<mark.a....@gmail.com> wrote:
>
>> Hi Andre,
>> Thanks for that. I changed to visual.Window and that solved that problem, but now I have a new error:
>>
>> win.push_handlers(keyboard)
>> AttributeError: class Window has no attribute 'push_handlers'
>>
>> Any thoughts on that one?
>> Thanks,
>> Mark
>>
>> On Tuesday, April 16, 2013 11:28:42 PM UTC+9, Andre Gouws wrote:
>> should probably be "visual.Window" not "window.Window"
>>
>>
>> On Tue, Apr 16, 2013 at 3:01 PM, ShoinExp<mark.a....@gmail.com> wrote:
>> Hi Dave,
>> This is an old post, but I'm trying to do the same thing. I'm not a coder at all, so I'm cutting, pasting and praying. When I added your code to my experiment (which at the moment is just a single trial with a single keyboard-event so that I can play around with getting your code working), I got the following error:
>>
>> win = window.Window
>> NameError: name 'window' is not defined

--
Jonathan Peirce
Nottingham Visual Neuroscience

http://www.peirce.org.uk

This message and any attachment are intended solely for the addressee and may contain confidential information. If you have received this message in error, please send it back to me, and immediately delete it. Please do not use, copy or disclose the information contained in this message or in any attachment. Any views or opinions expressed by the author of this email do not necessarily reflect the views of the University of Nottingham.

This message has been checked for viruses but the contents of an attachment
may still contain software viruses which could damage your computer system:
you are advised to perform your own checks. Email communications with the
University of Nottingham may be monitored as permitted by UK legislation.

ShoinExp

unread,
Apr 17, 2013, 4:40:20 AM4/17/13
to psychop...@googlegroups.com
Hi Mike,
    Thanks for your suggestion.  I'm sure you're right that that was an error, but it clearly wasn't the only one because I'm now getting a slightly different error message:

 win.push_handlers(keyboard)
AttributeError: Window instance has no attribute 'push_handlers'

     Thanks,
     Mark


On Wednesday, April 17, 2013 12:32:48 PM UTC+9, Michael MacAskill wrote:

This is a class (i.e. the definition of what a Window is and what it does):
visual.Window

This is a function that returns an actual instance of a class that you can actually do things with:
visual.Window()

You want the second one.

Mike


On 17 Apr, 2013, at 14:13, ShoinExp <mark.a....@gmail.com> wrote:

> Hi Andre,
>     Thanks for that.  I changed to visual.Window and that solved that problem, but now I have a new error:
>
> win.push_handlers(keyboard)
> AttributeError: class Window has no attribute 'push_handlers'
>
>     Any thoughts on that one?
>     Thanks,
>     Mark
>
> On Tuesday, April 16, 2013 11:28:42 PM UTC+9, Andre Gouws wrote:
> should probably be "visual.Window" not "window.Window"
>
>
> On Tue, Apr 16, 2013 at 3:01 PM, ShoinExp <mark.a....@gmail.com> wrote:
> Hi Dave,
>     This is an old post, but I'm trying to do the same thing.  I'm not a coder at all, so I'm cutting, pasting and praying.  When I added your code to my experiment (which at the moment is just a single trial with a single keyboard-event so that I can play around with getting your code working), I got the following error:
>
>   win = window.Window
> NameError: name 'window' is not defined

--
Michael R. MacAskill, PhD                michael.maca...@nzbri.org

Jeremy Gray

unread,
Apr 17, 2013, 8:00:20 AM4/17/13
to psychop...@googlegroups.com
Dave's original post was from the pyglet documentation, not the
psychopy documentation. There are differences, and you'll have to
adapt things, and keep track of the namespaces. The following is a
start:

>>> from psychopy import visual
>>> win = visual.Window()
>>> win
<psychopy.visual.Window instance at 0x11fc468> # psychopy

>>> win.winHandle
<pyglet.window.carbon.CarbonWindow object at 0x600e6b0> # pyglet

>>> import pyglet
>>> key = pyglet.window.key # needed for key.UP, and so on
>>> keyboard = key.KeyStateHandler()
>>> win.winHandle.push_handlers(keyboard)
>> Michael R. MacAskill, PhD michael....@nzbri.org
>> Research Director,
>> New Zealand Brain Research Institute
>>
>> 66 Stewart St
>> http://www.nzbri.org/macaskill
>> Christchurch 8011 Ph: +64 3 3786
>> 072
>> NEW ZEALAND Fax: +64 3 3786 080
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
> --
> You received this message because you are subscribed to the Google Groups
> "psychopy-users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to psychopy-user...@googlegroups.com.
> To post to this group, send email to psychop...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/psychopy-users/-/DQWD0VjxAjUJ.

ShoinExp

unread,
Apr 18, 2013, 9:27:27 AM4/18/13
to psychop...@googlegroups.com
Hi Jeremy,
    Thanks for the help.  I'll play around with the code.
    Thanks,
    Mark

Rich

unread,
Sep 17, 2013, 8:04:29 PM9/17/13
to psychop...@googlegroups.com
I know this is an old post, but I'm trying to do the same thing. My understanding of psychopy is rudimentary at best, but so far I think I've figured out I need to import key from pyglet. My code is:

import pyglet
key = pyglet.window.key
keyboard = key.KeyStateHandler()
win.winHandle.push_handlers(keyboard)

This import code seems to work without errors. But in my experiment, I use:

keyboard(key.A) and get the following error:

####TypeError:'KeyStateHandler' object is not callable.

Any suggestions on what I'm doing wrong?

Rich

Jared Roberts

unread,
Sep 17, 2013, 8:19:18 PM9/17/13
to psychop...@googlegroups.com
Hi Rich,

The KeyStateHandler isn't a function, but rather a dict.  A dict is a special type of list that uses strings as indexes rather than numbers.  Basically, you need to index key.A rather than try to pass it as a variable.  That means that you need to use [ ] instead of ( ). 

keyboard[key.A]  - which will be True if the key is currently down, and False if it is currently up.

http://www.pyglet.org/doc/api/pyglet.window.key.KeyStateHandler-class.html

-Jared



For more options, visit https://groups.google.com/groups/opt_out.



--
Jared Roberts
Graduate Student
The Yassa Learning and Memory Laboratory
Johns Hopkins University
"A lost cause can be as spiritually satisfying as a victory." - Robert Heinlein

Rich

unread,
Sep 17, 2013, 8:45:36 PM9/17/13
to psychop...@googlegroups.com
Ah, thankyou!

Sol Simpson

unread,
Sep 18, 2013, 8:57:23 AM9/18/13
to psychop...@googlegroups.com
Or you could use psychopy.iohub instead of a pyglet KeyStateHandler and get key press durations already calculated for you. The durations will be of better accuracy in cases where you are checking for key state changes within a loop that is calling flip() every iteration as well, since the duration calculation is not limiting the granularity of the key durations to the retrace rate of your system. See demos.coder.iohub_basic.iohub_heybaord for a full example. 


from psychopy.iohub import launchHubServer,EventConstants,

io
=launchHubServer(psychopy_monitor_name='default')
keyboard
= io.devices.keyboard

# Create you PsychoPy Window and and do other stuff needed to setup your exp....
#....


# When you want to start getting key events, discarding any previous events call...
io
.clearEvents('all')

# Each time you want to check for key press - release combinations
# and get the duration etc. 
do as follows...
for event in keyboard.getEvents():
   
if event.type == EventConstants.KEYBOARD_CHAR:
       
# KEYBOARD_CHAR events are created only after a key is press and then released.
       
# access the key press - release duration...
        key_press_duration
=event.duration
       
# access also can access other event details:
        key_press_start_time
=event.press_event.time
 
       key_release_time=event.time
 
               # For visible keys,key is the unicode char value (i.e. 'a', '+', '1', etc.), and for non visible keys it is a str constant (i.e. 'DOWN', 'UP', 'HOME', 'PAGE_DOWN', etc.). 
                key=event.key

# If you also need to calculate the RT from a stim. onset to when the key started to be pressed it would go something like:

# draw your stim..
# .....

flip_time=win.flip()

# Use code above to get 
KEYBOARD_CHAR events.
# ......

 The RT for each 
KEYBOARD_CHAR  event from the stim onset =:
rt_in_secs=event.press_event.time - flip_time


Thanks,

Sol

Rich

unread,
Sep 27, 2013, 1:31:06 AM9/27/13
to psychop...@googlegroups.com
Hi Sol, that's interesting. Can iohub detect events from a serial-to-usb connection? I would like to use it for an fMRI experiment to detect the button state (down or up) and press durations from my MRI-compatible button box. I can use the code you provided for keyboard events, but can't get it to work for my MRI button box.

Cheers,

Rich


Sol Simpson

unread,
Sep 27, 2013, 11:24:41 AM9/27/13
to psychop...@googlegroups.com
Hey Rich,

What MRI Bbox are you using? If the box is actually emulating a keyboard, so the OS itself thinks the input is from an actual KB, then it should work. 

If you are running windows, and the box is getting some device specific input , which is likely if you need to use a serial to usb converter, and then creating kb events at a user space level, then ioHub will not detect the kb events. iohub gets the kb events prior to the event being registered in the window event queue on win32, which is a + for event time calculation, but a - for your situation. ;(.   

If you are in the latter situation, then it would be possible to add support for the Bbox if we can get the serial protocol details being used by the hardware. We could then either create a new device type for the box (so you would know if the box vs. a real kb attached to the PC generated one of the mapped key events), or make it like what is being done now from the sounds of it, and create iohub keyboard device events based on the serial input read.

Let me know if you need for info.

Thanks,

Sol 

Rich

unread,
Sep 27, 2013, 8:11:17 PM9/27/13
to psychop...@googlegroups.com
Thanks Sol. I'm using a cedrus/lumina response box which you and Jared pointed out that is compatible with pyxid on another post I made on this topic. I'll look into that the first chance I get. Cheers, Rich

Jenny Tellett

unread,
Oct 9, 2013, 5:02:26 AM10/9/13
to psychop...@googlegroups.com
Hi Sol,

I am trying to use the iohub but as I am very much a beginner in terms of coding, was adding it into my experiment in the builder using a code component. I would like to use iohub as I need to record keyboard release RTs rather than press RTs and this looks as though it is fairly straight forward using iohub. However, I am having problems getting the iohub to work in the first instance. I have tried putting these lines from your example into the 'begin experiment' box so that it calls the iohub:

from psychopy.iohub import launchHubServer,EventConstants

io
=launchHubServer(psychopy_monitor_name='default')
keyboard 
= io.devices.keyboard

But that results in the following error: 

<class 'psychopy.iohub.util.exception_tools.ioHubError'>
ioHubError:
Args: ('Error during device creation ....',)

I have also looked at other examples and the documentation and tried some different options, but these result in either the same error message, or similar messages where it is unable to find the iohub. So my questions are; is the iohub be integrated into the 1.77.02 version of psychopy that I am running (in fact what is the earliest version that it works with)? Can I call to it using a code component in builder rather than writing the whole thing in coder? What is the best piece of code to use to call it in the first instance?

Any help will be greatly appreciated,

Jenny

Sol Simpson

unread,
Oct 9, 2013, 4:42:48 PM10/9/13
to psychop...@googlegroups.com
Hi Jenny,

You can add iohub support within a Builder project by using a custom code component. So that should not be the issue.
- What OS are you using? 
- Can you upgrade to the latest PsychoPy version (1.78.xx), as that has iohub built in and working for sure. 
- I do not recall what version of psychopy first had a functional psychopy.iohub module. If this is critical I can dig through the commit logs and see what a likely 1.77.xx version that works would be.

If you are still having trouble, I can likely put together a simple Builder example that calculates reaction time and key press time from some stim onset. Let me know.

Thanks,

Sol

Jenny Tellett

unread,
Oct 10, 2013, 10:15:04 AM10/10/13
to psychop...@googlegroups.com
Hi Sol,

Thanks for the reply. I tried updating to the latest version and get the same error - it seems as though I am not using the correct command to find the iohub, or it is not in the right place or something. I am running on Mac OS 10.8.3.

Thanks,

Jenny

Sol Simpson

unread,
Oct 10, 2013, 6:32:58 PM10/10/13
to psychop...@googlegroups.com
Hi Jenny,

Can you try creating a simple python script with the following in it and let me know if this runs? Also please be sure that you have checked "enable access for assistive devices" in the OS X System Preferences and headed over to the Accessibility Pane.

Might also be good to check that there are not any unexpected instances of the python.exe process running; kill any that are.

from psychopy.iohub import launchHubServer

io
=launchHubServer(psychopy_monitor_name='default')
keyboard
= io.devices.keyboard

print "ioHub Started.... Press Any Key to Exit"

io
.clearEvents()
while not keyboard.getEvents():
    io
.wait(0.25)

io
.quit()


If this does not work, please send the full stack trace for the error that should be printed to the console window.


Thanks again,


Sol


m.kno...@iwm-kmrc.de

unread,
Oct 21, 2013, 9:10:53 AM10/21/13
to psychop...@googlegroups.com
Hello Sol,

Sounds very interesting. But where do i have to put the keyboard.getEvents(): loop inside the builder.
Inside 'each Frame'?
Thanks for any hint.

Manfred

Sol Simpson

unread,
Oct 22, 2013, 3:28:58 PM10/22/13
to psychop...@googlegroups.com
Hi Manfred,

Sorry for the delay in reply.

Yes, that is correct. I have attached a modified version of the stroop demo builder project that shows how to use a custom code component so the iohub keyboard device can be used to collect reaction times, key press durations, response validity, control trial end time, and save these measures to psychopy data files.

Unzip the attachment, open the unpacked stroop_keyboard folder and open the Builder project file in it.

Thanks.

Sol  
stroop_keyboard.zip

m.kno...@iwm-kmrc.de

unread,
Oct 23, 2013, 7:14:34 AM10/23/13
to psychop...@googlegroups.com
Hi Sol,

thanks a lot. When i use your code inside the experiment i'm running into problems:

Currently i'm testing on Windows 7, the experiments are developed by our scientists on OS X, the participants will
work on Windows XP.
My current problem on Windows 7:

A Keyboard Component used prior to the iohub_keyboard does no longer work i.e. seems to take no input.
This is the case even when i use your stroop example.

During my own efforst fixing this i put the initialisation of the keybord to 'begin routine', consequently i tried
to put the io.quit() to 'end routine'. So no side effects hurt the prior or following keyboard usages. But the script reacts very
slowly and i'm getting 'Warning: TimeoutExpired, Killing ioHub Server process' in coder output window.
Any ideas to enhance this?

ot: trials.addData('resp.corr', response_event.key.lower()==corrAns) <- not initialised / variable not bound in the stroop example

regards from
Manfred Knobloch

m.kno...@iwm-kmrc.de

unread,
Oct 23, 2013, 9:46:39 AM10/23/13
to psychop...@googlegroups.com
Addition to my recent post:
adding a
iokeyboard.clearEvents()

to routine end removes the warning described below.

regards
Manfred

Jonathan Peirce

unread,
Oct 23, 2013, 9:54:45 AM10/23/13
to psychop...@googlegroups.com
I think it would be wise not to mix keyboard checking from iohub with
keyboard checking from pyglet. Unexpected things might happen.
Jon

On 23/10/2013 12:14, m.kno...@iwm-kmrc.de wrote:
> A Keyboard Component used prior to the iohub_keyboard does no longer
> work i.e. seems to take no input.
> This is the case even when i use your stroop example.

--
Jonathan Peirce
Nottingham Visual Neuroscience

http://www.peirce.org.uk

This message and any attachment are intended solely for the addressee and may contain confidential information. If you have received this message in error, please send it back to me, and immediately delete it. Please do not use, copy or disclose the information contained in this message or in any attachment. Any views or opinions expressed by the author of this email do not necessarily reflect the views of the University of Nottingham.

This message has been checked for viruses but the contents of an attachment
may still contain software viruses which could damage your computer system, you are advised to perform your own checks. Email communications with the University of Nottingham may be monitored as permitted by UK legislation.




m.kno...@iwm-kmrc.de

unread,
Oct 23, 2013, 10:14:03 AM10/23/13
to psychop...@googlegroups.com
ok, i really like to be wise ;-) but unfortunately as i have described: the psyexp file only comes to me after the scientists prepared the trials and met a requirement they could not realize in builder.

The solution would be to have a TimeMeasuredKeyBoard Component that can be configured in builder without coding.
Or did i miss something?
best regards

Manfred

Sol Simpson

unread,
Oct 23, 2013, 6:46:14 PM10/23/13
to psychop...@googlegroups.com
Hi Manfred,

Does the example I sent run as is, without any changes made to it, and the issue is when you try and integrate the code component into your own example? I used Windows 7 when developing the example, so it should be OK.

If you get errors using the example I sent, can you get Builder to create the Coder script for the project, and then run the created python script from coder? Please send the script that is being generated along with the error you get. Also, are you using the latest psychopy source version from github? If not, please let me know what version you are running.

If my example runs fine, but when you use the code in your own project you get issues, please send the project and I can try it here and try to see what is going on.

Also, check that there are not any 'orphan' python processes running on the computer by checking the process list in task manager and killing any unexpected python.exe processes. Currently there is an issue when using iohub from within the PsychoPy GUI if you manually terminate the experiment by pressing the 'Stop' button while the program is still running. When this is done, the iohub process is not told to shut down, so it just keeps running after you force exit the psychopy runtime process. So  for now avoid using that button when using ioHub until the issue is resolved. ;)

Thanks again.

Sol

Sol Simpson

unread,
Oct 23, 2013, 7:05:14 PM10/23/13
to psychop...@googlegroups.com
Definitely do not mix using keyboard events from pyglet with those when doing any event comparison / calculation / analysis. The two event systems are completely independent so events from one can not be compared to the other.

Technically though, there is no reason why iohub can not be used to get keyboard events in the same experiment that uses pyglet keyboard events for other purposes. For example, if you are using pyglet kb events to know when to move from a user message / information type screen and using iohub keyboard events during the trial sequence that you need to get key duration from, this should not cause any problems. 

The iohub event system can (and currently does) run at the same time the pyglet event system is running; this happens anytime iohub is used at all, for any device. The two event processing systems do not interact in any way from a technical POV. For example, the demos.coder.iohub_basic.iohub_keyboard demo script gets keyboard events from iohub for the demo. However the pyglet event system is having dispatchEvents() called every time win.flip() is called. The pyglet events are not being used by the demo, but they are still being process by pyglet and any pyglet event handlers created by psychopy are still being called. Currently there is no way to tell psychopy to 'turn off' pyglet event monitoring for redundant event types.

Hopefully whenever iohub is integrated fully enough with psychopy we can turn off the pyglet event system when iohub is being used and save the redundant event processing overhead (whatever little amount there is), but for now the two running in at the same time works just fine.

Thanks again,

Sol 

m.kno...@iwm-kmrc.de

unread,
Oct 24, 2013, 2:28:58 AM10/24/13
to psychop...@googlegroups.com
Hi Sol,

the example you sent me starts, but after the explanation Text it hangs. There is no reaction when i try to 'press any key to continue'.
I'm not getting any error message. I'm not even running up to

trials.addData('resp.corr', response_event.key.lower()==corrAns)

Only when i copied this code into my own script i received the message that corrAns is not initialised.
The same applies to 'compiling' and running from coder (stroop.py attached).

So i pressed the stop button and sure got many python zombies in my task list.

Whats running for me now is a mixture. In the prior trials (defined by the scientists) normal keyboard Component is used.

Then in the section where the duration (german: Zeitdauer) of a space key press is assumed i do the following:
(own code parts are inserted by coder window inside Builder; inserted code is marked in comments, Begin Experiment, prior and following Trials left out)

...
for thisTrial in trials:
    currentLoop = trials
    # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
    if thisTrial != None:
        for paramName in thisTrial.keys():
            exec(paramName + '= thisTrial.' + paramName)
   
    #------Prepare to start Routine "Zeitdauer"-------
    t = 0
    ZeitdauerClock.reset()  # clock
    frameN = -1
    # update component parameters for each repeat
    movie = visual.MovieStim(win=win, name='movie',
        filename=displayed_clipFile,
        ori=0, pos=[0, 0], opacity=1,
        size=[1200, 900],
        depth=0.0,
        )

    # ---------- code on Begin routine ---------------
    io=ioHubConnection(io_config)
    iokeyboard=io.devices.keyboard
    iokeyboard.clearEvents()
    # ------------- inserted Code End
   
    # keep track of which components have finished
    ZeitdauerComponents = []
    ZeitdauerComponents.append(movie)
    ZeitdauerComponents.append(Zeittext)
    for thisComponent in ZeitdauerComponents:
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
   
    #-------Start Routine "Zeitdauer"-------
    continueRoutine = True
    while continueRoutine:
        # get current time
        t = ZeitdauerClock.getTime()
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame
       
        # *movie* updates
        if t >= 1.0 and movie.status == NOT_STARTED:
            # keep track of start time/frame for later
            movie.tStart = t  # underestimates by a little under one frame
            movie.frameNStart = frameN  # exact frame index
            movie.setAutoDraw(True)
       
        # *Zeittext* updates
        if t >= movie.status==FINISHED and Zeittext.status == NOT_STARTED:
            # keep track of start time/frame for later
            Zeittext.tStart = t  # underestimates by a little under one frame
            Zeittext.frameNStart = frameN  # exact frame index
            Zeittext.setAutoDraw(True)

        # ------- inserted Code each frame ------------------------------
        if Zeittext.status == STARTED:
            for kb_event in iokeyboard.getEvents():
                if kb_event.type == EventConstants.KEYBOARD_CHAR and kb_event.key == u' ':
                    continueRoutine = False
                    trials.addData("assumed_duration", kb_event.duration)
        # ------------- inserted Code End
       
        # check if all components have finished
        if not continueRoutine:  # a component has requested a forced-end of Routine
            routineTimer.reset()  # if we abort early the non-slip timer needs reset
            break
        continueRoutine = False  # will revert to True if at least one component still running
        for thisComponent in ZeitdauerComponents:
            if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished
       
        # check for quit (the [Esc] key)
        if event.getKeys(["escape"]):
            core.quit()
       
        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()
        else:  # this Routine was not non-slip safe so reset non-slip timer
            routineTimer.reset()
   
    #-------Ending Routine "Zeitdauer"-------
    for thisComponent in ZeitdauerComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)

    # ------------- Inserted Code End routine
    iokeyboard.clearEvents()
    io.clearEvents()
    io.quit()
    # ------------- Inserted Code End

    thisExp.nextEntry()
   
# completed 1 repeats of 'trials'
.......

This code was tested on Win 7 and XP, runs on both, but at the end of the experiment a popping up window states:
'ioHubServer Process completed With code:0'

best regards

Manfred
stroop.py

Sol Simpson

unread,
Oct 25, 2013, 7:32:47 AM10/25/13
to psychop...@googlegroups.com
Can you make sure to click on the window with the mouse when it is first displayed to make it active before pressing a key to continue onto the trial phase. I found that when the experiment starts, the window is not active, so pyglet is not getting keyboard events. I guess this happens because it is a non full screen window, not sure. Making sure the window is active allowed me to move from the first screen to others.
Reply all
Reply to author
Forward
0 new messages