psychopy.plugins - utilities for extending PsychoPy® with plugins

Overview

scanPlugins()

Scan the system for installed plugins.

listPlugins([which])

Get a list of installed or loaded PsychoPy plugins.

loadPlugin(plugin)

Load a plugin to extend PsychoPy.

requirePlugin(plugin)

Require a plugin to be already loaded.

isPluginLoaded(plugin)

Check if a plugin has been previously loaded successfully by a loadPlugin() call.

startUpPlugins(plugins[, add, verify])

Specify which plugins should be loaded automatically when a PsychoPy session starts.

isStartUpPlugin(plugin)

Check if a plugin is registered to be loaded when PsychoPy starts.

pluginMetadata(plugin)

Get metadata from a plugin package.

pluginEntryPoints(plugin[, parse])

Get the entry point mapping for a specified plugin.

computeChecksum(fpath[, method, writeOut])

Compute the checksum hash/key for a given package.

Details

psychopy.plugins.scanPlugins()[source]

Scan the system for installed plugins.

This function scans installed packages for the current Python environment and looks for ones that specify PsychoPy entry points in their metadata. Afterwards, you can call listPlugins() to list them and loadPlugin() to load them into the current session. This function is called automatically when PsychoPy starts, so you do not need to call this unless packages have been added since the session began.

Returns:

Number of plugins found during the scan. Calling listPlugins() will return the names of the found plugins.

Return type:

int

psychopy.plugins.listPlugins(which='all')[source]

Get a list of installed or loaded PsychoPy plugins.

This function lists either all potential plugin packages installed on the system, those registered to be loaded automatically when PsychoPy starts, or those that have been previously loaded successfully this session.

Parameters:

which (str) – Category to list plugins. If ‘all’, all plugins installed on the system will be listed, whether they have been loaded or not. If ‘loaded’, only plugins that have been previously loaded successfully this session will be listed. If ‘startup’, plugins registered to be loaded when a PsychoPy session starts will be listed, whether or not they have been loaded this session. If ‘unloaded’, plugins that have not been loaded but are installed will be listed. If ‘failed’, returns a list of plugin names that attempted to load this session but failed for some reason.

Returns:

Names of PsychoPy related plugins as strings. You can load all installed plugins by passing list elements to loadPlugin.

Return type:

list

See also

loadPlugin

Load a plugin into the current session.

Examples

Load all plugins installed on the system into the current session (assumes all plugins don’t require any additional arguments passed to them):

for plugin in plugins.listPlugins():
    plugins.loadPlugin(plugin)

If certain plugins take arguments, you can do this give specific arguments when loading all plugins:

pluginArgs = {'some-plugin': (('someArg',), {'setup': True, 'spam': 10})}
for plugin in plugins.listPlugins():
    try:
        args, kwargs = pluginArgs[plugin]
        plugins.loadPlugin(plugin, *args, **kwargs)
    except KeyError:
        plugins.loadPlugin(plugin)

Check if a plugin package named plugin-test is installed on the system and has entry points into PsychoPy:

if 'plugin-test' in plugins.listPlugins():
    print("Plugin installed!")

Check if all plugins registered to be loaded on startup are currently active:

if not all([p in listPlugins('loaded') for p in listPlugins('startup')]):
    print('Please restart your PsychoPy session for plugins to take effect.')
psychopy.plugins.loadPlugin(plugin)[source]

Load a plugin to extend PsychoPy.

Plugins are packages which extend upon PsychoPy’s existing functionality by dynamically importing code at runtime, without modifying the existing installation files. Plugins create or redefine objects in the namespaces of modules (eg. psychopy.visual) and unbound classes, allowing them to be used as if they were part of PsychoPy. In some cases, objects exported by plugins will be registered for a particular function if they define entry points into specific modules.

Plugins are simply Python packages,`loadPlugin` will search for them in directories specified in sys.path. Only packages which define entry points in their metadata which pertain to PsychoPy can be loaded with this function. This function also permits passing optional arguments to a callable object in the plugin module to run any initialization routines prior to loading entry points.

This function is robust, simply returning True or False whether a plugin has been fully loaded or not. If a plugin fails to load, the reason for it will be written to the log as a warning or error, and the application will continue running. This may be undesirable in some cases, since features the plugin provides may be needed at some point and would lead to undefined behavior if not present. If you want to halt the application if a plugin fails to load, consider using requirePlugin().

It is advised that you use this function only when using PsychoPy as a library. If using the builder or coder GUI, it is recommended that you use the plugin dialog to enable plugins for PsychoPy sessions spawned by the experiment runner. However, you can still use this function if you want to load additional plugins for a given experiment, having their effects isolated from the main application and other experiments.

Parameters:

plugin (str) – Name of the plugin package to load. This usually refers to the package or project name.

Returns:

True if the plugin has valid entry points and was loaded successfully. Also returns True if the plugin was already loaded by a previous loadPlugin call this session, this function will have no effect in this case. False is returned if the plugin defines no entry points specific to PsychoPy or crashed (an error is logged).

Return type:

bool

Warning

Make sure that plugins installed on your system are from reputable sources, as they may contain malware! PsychoPy is not responsible for undefined behaviour or bugs associated with the use of 3rd party plugins.

See also

listPlugins

Search for and list installed or loaded plugins.

requirePlugin

Require a plugin be previously loaded.

Examples

Load a plugin by specifying its package/project name:

loadPlugin('psychopy-hardware-box')

You can give arguments to this function which are passed on to the plugin:

loadPlugin('psychopy-hardware-box', switchOn=True, baudrate=9600)

You can use the value returned from loadPlugin to determine if the plugin is installed and supported by the platform:

hasPlugin = loadPlugin('psychopy-hardware-box')
if hasPlugin:
    # initialize objects which require the plugin here ...
psychopy.plugins.requirePlugin(plugin)[source]

Require a plugin to be already loaded.

This function can be used to ensure if a plugin has already been loaded and is ready for use, raising an exception and ending the session if not.

This function compliments loadPlugin(), which does not halt the application if plugin fails to load. This allows PsychoPy to continue working, giving the user a chance to deal with the problem (either by disabling or fixing the plugins). However, requirePlugin() can be used to guard against undefined behavior caused by a failed or partially loaded plugin by raising an exception before any code that uses the plugin’s features is executed.

Parameters:

plugin (str) – Name of the plugin package to require. This usually refers to the package or project name.

Raises:

RuntimeError – Plugin has not been previously loaded this session.

See also

loadPlugin

Load a plugin into the current session.

Examples

Ensure plugin psychopy-plugin is loaded at this point in the session:

requirePlugin('psychopy-plugin')  # error if not loaded

You can catch the error and try to handle the situation by:

try:
    requirePlugin('psychopy-plugin')
except RuntimeError:
    # do something about it ...
psychopy.plugins.isPluginLoaded(plugin)[source]

Check if a plugin has been previously loaded successfully by a loadPlugin() call.

Parameters:

plugin (str) – Name of the plugin package to check if loaded. This usually refers to the package or project name.

Returns:

True if a plugin was successfully loaded and active, else False.

Return type:

bool

See also

loadPlugin

Load a plugin into the current session.

psychopy.plugins.startUpPlugins(plugins, add=True, verify=True)[source]

Specify which plugins should be loaded automatically when a PsychoPy session starts.

This function edits psychopy.preferences.prefs.general['startUpPlugins'] and provides a means to verify if entries are valid. The PsychoPy session must be restarted for the plugins specified to take effect.

If using PsychoPy as a library, this function serves as a convenience to avoid needing to explicitly call loadPlugin() every time to use your favorite plugins.

Parameters:
  • plugins (str, list or None) – Name(s) of plugins to have load on startup.

  • add (bool) – If True names of plugins will be appended to startUpPlugins unless a name is already present. If False, startUpPlugins will be set to plugins, overwriting the previous value. If add=False and plugins=[] or plugins=None, no plugins will be loaded in the next session.

  • verify (bool) – Check if plugins are installed and have valid entry points to PsychoPy. Raises an error if any are not. This prevents undefined behavior arsing from invalid plugins being loaded in the next session. If False, plugin names will be added regardless if they are installed or not.

Raises:

RuntimeError – If verify=True, any of plugins is not installed or does not have entry points to PsychoPy. This is raised to prevent issues in future sessions where invalid plugins are written to the config file and are automatically loaded.

Warning

Do not use this function within the builder or coder GUI! Use the plugin dialog to specify which plugins to load on startup. Only use this function when using PsychoPy as a library!

Examples

Adding plugins to load on startup:

startUpPlugins(['plugin1', 'plugin2'])

Clearing the startup plugins list, no plugins will be loaded automatically at the start of the next session:

plugins.startUpPlugins([], add=False)
# or ..
plugins.startUpPlugins(None, add=False)

If passing None or an empty list with add=True, the present value of prefs.general[‘startUpPlugins’] will remain as-is.

psychopy.plugins.isStartUpPlugin(plugin)[source]

Check if a plugin is registered to be loaded when PsychoPy starts.

Parameters:

plugin (str) – Name of the plugin package to check. This usually refers to the package or project name.

Returns:

True if a plugin is registered to be loaded when a PsychoPy session starts, else False.

Return type:

bool

Examples

Check if a plugin was loaded successfully at startup:

pluginName = 'psychopy-plugin'
if isStartUpPlugin(pluginName) and isPluginLoaded(pluginName):
    print('Plugin successfully loaded at startup.')
psychopy.plugins.pluginMetadata(plugin)[source]

Get metadata from a plugin package.

Reads the package’s PKG_INFO and gets fields as a dictionary. Only packages that have valid entry points to PsychoPy can be queried.

Parameters:

plugin (str) – Name of the plugin package to retrieve metadata from.

Returns:

Metadata fields.

Return type:

dict

psychopy.plugins.pluginEntryPoints(plugin, parse=False)[source]

Get the entry point mapping for a specified plugin.

You must call scanPlugins before calling this function to get the entry points for a given plugin.

Note this function is intended for internal use by the PsychoPy plugin system only.

Parameters:
  • plugin (str) – Name of the plugin package to get advertised entry points.

  • parse (bool) – Parse the entry point specifiers and convert them to fully-qualified names.

Returns:

Dictionary of target groups/attributes and entry points objects.

Return type:

dict

psychopy.plugins.computeChecksum(fpath, method='sha256', writeOut=None)[source]

Compute the checksum hash/key for a given package.

Authors of PsychoPy plugins can use this function to compute a checksum hash and users can use it to check the integrity of their packages.

Parameters:
  • fpath (str) – Path to the plugin package or file.

  • method (str) – Hashing method to use, values are ‘md5’ or ‘sha256’. Default is ‘sha256’.

  • writeOut (str) – Path to a text file to write checksum data to. If the file exists, the data will be written as a line at the end of the file.

Returns:

Checksum hash digested to hexadecimal format.

Return type:

str

Examples

Compute a checksum for a package and write it to a file:

with open('checksum.txt', 'w') as f:
    f.write(computeChecksum(
        '/path/to/plugin/psychopy_plugin-1.0-py3.6.egg'))

Back to top