Starting the psychopy.iohub Process

To use ioHub within your PsychoPy Coder experiment script, ioHub needs to be started at the beginning of the experiment script.

The easiest way to do this is by calling the launchHubServer function.

launchHubServer Function


Starts the ioHub Server subprocess, and return a psychopy.iohub.client.ioHubConnection object that is used to access enabled iohub device’s events, get events, and control the ioHub process during the experiment.

By default (no kwargs specified), the ioHub server does not create an ioHub HDF5 file, events are available to the experiment program at runtime. The following Devices are enabled by default:

  • Keyboard: named ‘keyboard’, with runtime event reporting enabled.

  • Mouse: named ‘mouse’, with runtime event reporting enabled.

  • Monitor: named ‘monitor’.

  • Experiment: named ‘experiment’.

To customize how the ioHub Server is initialized when started, use one or more of the following keyword arguments when calling the function:


  1. Wait for the ‘q’ key to be pressed:

    from psychopy.iohub.client import launchHubServer
    # Start the ioHub process. 'io' can now be used during the
    # experiment to access iohub devices and read iohub device events.
    print("Press any Key to Exit Example.....")
    # Wait until a keyboard event occurs
    keys = io.devices.keyboard.waitForKeys(keys=['q',])
    print("Key press detected: {}".format(keys))
    print("Exiting experiment....")
    # Stop the ioHub Server

Please see the psychopy/demos/coder/iohub/ demo for examples of different ways to use the launchHubServer function.

ioHubConnection Class

The psychopy.iohub.ioHubConnection object returned from the launchHubServer function provides methods for controlling the iohub process and accessing iohub devices and events.

class psychopy.iohub.client.ioHubConnection(object)[source]

ioHubConnection is responsible for creating, sending requests to, and reading replies from the ioHub Process. This class is also used to shut down and disconnect the ioHub Server process.

The ioHubConnection class is also used as the interface to any ioHub Device instances that have been created so that events from the device can be monitored. These device objects can be accessed via the ioHubConnection .devices attribute, providing ‘dot name’ access to enabled devices. Alternatively, the .getDevice(name) method can be used and will return None if the device name specified does not exist.

Using the .devices attribute is handy if you know the name of the device to be accessed and you are sure it is actually enabled on the ioHub Process.

An example of accessing a device using the .devices attribute:

# get the Mouse device, named mouse
mouse_position = mouse.getPosition()

print 'mouse position: ', mouse_position

# Returns something like:
# >> mouse position:  [-211.0, 371.0]

Returns the ioHubDeviceView that has a matching name (based on the device : name property specified in the ioHub_config.yaml for the experiment). If no device with the given name is found, None is returned. Example, accessing a Keyboard device that was named ‘kb’

keyboard = self.getDevice('kb')
kb_events= keyboard.getEvent()

This is the same as using the ‘natural naming’ approach supported by the .devices attribute, i.e:

keyboard = self.devices.kb
kb_events= keyboard.getEvent()

However the advantage of using getDevice(device_name) is that an exception is not created if you provide an invalid device name, or if the device is not enabled on the ioHub server; None is returned instead.


deviceName (str) – Name given to the ioHub Device to be returned


The ioHubDeviceView instance for deviceName.

getEvents(device_label=None, as_type='namedtuple')[source]

Retrieve any events that have been collected by the ioHub Process from monitored devices since the last call to getEvents() or clearEvents().

By default all events for all monitored devices are returned, with each event being represented as a namedtuple of all event attributes.

When events are retrieved from an event buffer, they are removed from that buffer as well.

If events are only needed from one device instead of all devices, providing a valid device name as the device_label argument will result in only events from that device being returned.

Events can be received in one of several object types by providing the optional as_type property to the method. Valid values for as_type are the following str values:

  • ‘list’: Each event is a list of ordered attributes.

  • ‘namedtuple’: Each event is converted to a namedtuple object.

  • ‘dict’: Each event converted to a dict object.

  • ‘object’: Each event is converted to a DeviceEvent subclass

    based on the event’s type.

  • device_label (str) – Name of device to retrieve events for. If None ( the default ) returns device events from all devices.

  • as_type (str) – Returned event object type. Default: ‘namedtuple’.


List of event objects; object type controlled by ‘as_type’.

Return type



Clears unread events from the ioHub Server’s Event Buffer(s) so that unneeded events are not discarded.

If device_label is ‘all’, ( the default ), then events from both the ioHub Global Event Buffer and all Device Event Buffer’s are cleared.

If device_label is None then all events in the ioHub Global Event Buffer are cleared, but the Device Event Buffers are unaffected.

If device_label is a str giving a valid device name, then that Device Event Buffer is cleared, but the Global Event Buffer is not affected.


device_label (str) – device name, ‘all’, or None



sendMessageEvent(text, category='', offset=0.0, sec_time=None)[source]

Create and send an Experiment MessageEvent to the ioHub Server for storage in the ioDataStore hdf5 file.


MessageEvents can be thought of as DeviceEvents from the virtual PsychoPy Process “Device”.

  • text (str) – The text message for the message event. 128 char max.

  • category (str) – A str grouping code for the message. Optional. 32 char max.

  • offset (float) – Optional sec.msec offset applied to the message event time stamp. Default 0.

  • sec_time (float) – Absolute sec.msec time stamp for the message in. If not provided, or None, then the MessageEvent is time stamped when this method is called using the global timer (core.getTime()).



Return type


createTrialHandlerRecordTable(trials, cv_order=None)[source]

Create a condition variable table in the ioHub data file based on the a psychopy TrialHandler. By doing so, the iohub data file can contain the DV and IV values used for each trial of an experiment session, along with all the iohub device events recorded by iohub during the session.

Example psychopy code usage:

# Load a trial handler and
# create an associated table in the iohub data file
from import TrialHandler, importConditions

trials = TrialHandler(exp_conditions, 1)

# Inform the ioHub server about the TrialHandler

# Read a row of the trial handler for
# each trial of your experiment
for trial in trials:
    # do whatever...

# During the trial, trial variable values can be updated

# At the end of each trial, before getting
# the next trial handler row, send the trial
# variable states to iohub so they can be stored for future
# reference.

Adds the values from a TriaHandler row / record to the iohub data file for future data analysis use.






Deprecated Method: Use Computer.getTime instead. Remains here for testing time bases between processes only.

setPriority(level='normal', disable_gc=False)[source]

See Computer.setPriority documentation, where current process will be the iohub process.


See Computer.getPriority documentation, where current process will be the iohub process.


Returns the current ioHub Process affinity setting, as a list of ‘processor’ id’s (from 0 to getSystemProcessorCount()-1). A Process’s Affinity determines which CPU’s or CPU cores a process can run on. By default the ioHub Process can run on any CPU or CPU core.

This method is not supported on OS X at this time.




A list of integer values between 0 and

Computer.getSystemProcessorCount()-1, where values in the list indicate processing unit indexes that the ioHub process is able to run on.

Return type



Sets the ioHub Process Affinity based on the value of processor_list.

A Process’s Affinity determines which CPU’s or CPU cores a process can run on. By default the ioHub Process can run on any CPU or CPU core.

The processor_list argument must be a list of ‘processor’ id’s; integers in the range of 0 to Computer.processing_unit_count-1, representing the processing unit indexes that the ioHub Server should be allowed to run on.

If processor_list is given as an empty list, the ioHub Process will be able to run on any processing unit on the computer.

This method is not supported on OS X at this time.


processor_list (list) – A list of integer values between 0 and Computer.processing_unit_count-1, where values in the list indicate processing unit indexes that the ioHub process is able to run on.




Manually tell the ioDataStore to flush any events it has buffered in memory to disk.”.





startCustomTasklet(task_name, task_class_path, **class_kwargs)[source]

Instruct the iohub server to start running a custom tasklet given by task_class_path. It is important that the custom task does not block for any significant amount of time, or the processing of events by the iohub server will be negatively effected.

See the demo for an example of how to make a long running task not block the rest of the iohub server.


Instruct the iohub server to stop the custom task that was previously started by calling self.startCustomTasklet(….). task_name identifies which custom task should be stopped and must match the task_name of a previously started custom task.


Tells the ioHub Server to close all ioHub Devices, the ioDataStore, and the connection monitor between the PsychoPy and ioHub Processes. Then end the server process itself.






Same as the shutdown() method, but has same name as PsychoPy core.quit() so maybe easier to remember.

_startServer(ioHubConfig=None, ioHubConfigAbsPath=None)[source]

Starts the ioHub Process, storing it’s process id, and creating the experiment side device representation for IPC access to public device methods.


Create client side iohub device views.

_addDeviceView(dev_cls_name, dev_config)[source]

Add an iohub device view to self.devices


General purpose local <-> iohub server process UDP based request - reply code. The method blocks until the request is fulfilled and and a response is received from the ioHub server.


tx_data (tuple) – data to send to iohub server

Return (object): response from the ioHub Server process.


Sends the experiment info from the experiment config file to the ioHub Server, which passes it to the ioDataStore, determines if the experiment already exists in the hdf5 file based on ‘experiment_code’, and returns a new or existing experiment ID based on that criteria.


Sends the experiment session info from the experiment config file and the values entered into the session dialog to the ioHub Server, which passes it to the ioDataStore.

The dataStore determines if the session already exists in the experiment file based on ‘session_code’, and returns a new session ID if session_code is not in use by the experiment.

static _isErrorReply(data)[source]

Check if an iohub server reply contains an error that should be raised by the local process.

Back to top