Inline_script functions
class inline_script
Allows users to use Python code in their experiments.
When you are using the inline_script item, you are essentially writing
the body of two functions (prepare
and run
) of an inline_script
object. The inline_script
object has many more functions which you can
use, and these are listed below. To use these functions, you use the
self.[function_name]
notation.
Important note:
All inline_script items share the same workspace. This means that variables that are created in one inline_script are available in another inline_script. Similarly, modules that are imported in one inline_script are available in all other inline_scripts.
Example:
subject_nr = self.get("subject_nr")
Example:
self.sleep(1000)
Function list:
- function inline_script.auto_type(val)
- function inline_script.color_check(col)
- function inline_script.copy_sketchpad(sketchpad_name)
- function inline_script.eval_text(text, soft_ignore=False, round_float=False, quote_str=False)
- function inline_script.flush_log()
- function inline_script.from_string(string)
- function inline_script.get(var, _eval=True)
- function inline_script.get_check(var, default=None, _eval=True, valid=None)
- function inline_script.get_refs(text)
- function inline_script.has(var)
- function inline_script.log(msg)
- function inline_script.offline_canvas(auto_prepare=True)
- function inline_script.prepare()
- function inline_script.resolution()
- function inline_script.run()
- function inline_script.sanitize(s, strict=False, allow_vars=True)
- function inline_script.set(var, val)
- function inline_script.set_response(response=None, response_time=None, correct=None)
- function inline_script.sleep(ms)
- function inline_script.time()
- function inline_script.unistr(val)
- function inline_script.unset(var)
- function inline_script.usanitize(s, strict=False)
function inline_script.auto_type(val)
Converts a value into the ‘best fitting’ or ‘simplest’ type that is compatible with the value.
Arguments:
val
– A value. This can be any type.
Returns:
The same value converted to the ‘best fitting’ type.
- Type: unicode, int, float
function inline_script.color_check(col)
Checks whether a string is a valid color name. Raises an exception if col
is not a valid color.
Example:
# Ok
print(self.color_check('red'))
# Ok
print(self.color_check('#FFFFFF'))
# Raises osexception
print(self.color_check('this is not a color'))
Arguments:
col
– The color to check.
function inline_script.copy_sketchpad(sketchpad_name)
Creates a canvas that is a copy from the canvas of a sketchpad item.
Example:
my_canvas = self.copy_sketchpad('my_sketchpad')
Arguments:
sketchpad_name
– The name of the sketchpad.- Type: str, unicode
Returns:
A canvas.
- Type: canvas
function inline_script.eval_text(text, soft_ignore=False, round_float=False, quote_str=False)
Evaluates a string of text, so that all variable references (e.g., ‘[var]’) are replaced by values.
Example:
exp.set('var', 'evaluated')
print(self.eval_text('This string has been [var]'))
# Prints 'This string has been evaluated
Arguments:
text
– The text to be evaluated. This can be any type, but only str and unicode types will be evaluated.
Keywords:
round_float
– A Boolean indicating whether float values should be rounded to a precision of [round_decimals]. round_decimals is an OpenSesame variable that has a default value of 2.- Type: bool
- Default: False
soft_ignore
– A Boolean indicating whether missing variables should be ignored, rather than cause an exception.- Type: bool
- Default: False
quote_str
– A Boolean indicating whether string variables should be surrounded by single quotes (default=False).- Type: bool
- Default: False
Returns:
The evaluated text.
- Type: unicode, int, float
function inline_script.flush_log()
Forces any pending write operations to the log file to be written to disk.
Example:
self.log('TRIAL FINISHED')
self.flush_log()
function inline_script.from_string(string)
Parses the item from a definition string.
Arguments:
string
– A definition string, or None to reset the item.- Type: str, NoneType
function inline_script.get(var, _eval=True)
Returns the value of an OpenSesame variable. Checks first if the variable exists ‘locally’ in the item and, if not, checks if the variable exists ‘globally’ in the experiment.
The type of the returned value can be int, float, or unicode (string). The appropriate type is automatically selected, e.g. ‘10’ is returned as int, ‘10.1’ as float, and ‘some text’ as unicode.
The _eval parameter is used to specify whether the value of the variable should be evaluated, in case it contains references to other variables. This is best illustrated by example 2 below.
Example:
# Example 1
if self.get('cue') == 'valid':
print('This is a validly cued trial')
# Example 2
exp.set('var1', 'I like [var2]')
exp.set('var2', 'OpenSesame')
print(self.get('var1')) # prints 'I like OpenSesame'
print(self.get('var1', _eval=False)) # prints 'I like [var2]'
Arguments:
var
– The name of an OpenSesame variable.- Type: str, unicode
Keywords:
_eval
– Indicates whether the variable should be evaluated, i.e. whether containing variables should be processed.- Type: bool
- Default: True
Returns:
The value.
- Type: unicode, int, float
function inline_script.get_check(var, default=None, _eval=True, valid=None)
Similar to get(), but falls back to a default if the variable has not been set. It also raises an error if the value is not part of the valid list.
Example:
if self.get_check('cue', default='invalid') == 'valid':
print('This is a validly-cued trial')
Arguments:
var
– The name of an OpenSesame variable- Type: unicode, str
Keywords:
default
– A default ‘fallback’ value or None for no fallback, in which case an exception is rased if the variable does not exist.- Type: unicode, float, int
- Default: None
valid
– A list of allowed values (or None for no restrictions). An exception is raised if the value is not an allowed value.- Type: list, NoneType
- Default: None
_eval
– Indicates whether the variable should be evaluated, i.e. whether containing variables should be processed.- Type: bool
- Default: True
Returns:
The value
- Type: unicode, float, int
function inline_script.get_refs(text)
Returns a list of variables that are referred to by a string of text.
Arguments:
text
– A string of text. This can be any type, but will coerced to unicode if it is not unicode.
Returns:
A list of variable names or an empty list if the string contains no references.
- Type: list
function inline_script.has(var)
Checks if an OpenSesame variable exists, either in the item or in the experiment.
Example:
if not self.has('response'):
print('No response has been collected yet')
Arguments:
var
– The name of an OpenSesame variable.- Type: str, unicode
Returns:
True if the variable exists, False if not.
- Type: bool
function inline_script.log(msg)
Writes a message to the log file. Note that using the log()
function in combination with a logger item may result in messy log files.
Example:
self.log('TIMESTAMP = %s' % self.time())
Arguments:
msg
– A message. This can be any type and will we be converted to a unicode string using the logic described in unistr.
function inline_script.offline_canvas(auto_prepare=True)
Creates an empty canvas.
Example:
my_canvas = self.offline_canvas()
Keywords:
auto_prepare
– Seeopenexp.canvas.__init__
.- Type: bool
- Default: True
Returns:
A canvas.
- Type: canvas
function inline_script.prepare()
Executes the prepare script. The code that you enter in the ‘prepare’ tab of an inline_script item in the GUI is used as a body for this function.
function inline_script.resolution()
Returns the display resolution and checks whether the resolution is valid.
Important note:
The meaning of ‘resolution’ depends on the back-end. For example, the legacy back-end changes the actual resolution of the display, whereas the other back-ends do not alter the actual display resolution, but create a ‘virtual display’ with the requested resolution that is presented in the center of the display.
Returns:
A (width, height) tuple
- Type: tuple
function inline_script.run()
Executes the run script. The code that you enter in the ‘run’ tab of an inline_script item in the GUI is used as a body for this function.
function inline_script.sanitize(s, strict=False, allow_vars=True)
Removes invalid characters (notably quotes) from the string.
Example:
# Prints 'Universit Aix-Marseille'
print(self.sanitize('"Université Aix-Marseille"'))
# Prints 'UniversitAixMarseille'
print(self.sanitize('"Université Aix-Marseille""', strict=True))
Arguments:
s
– The string to be sanitized. This can be any type, but if it is not unicode, it will be coerced to unicode.
Keywords:
strict
– If True, all except underscores and alphanumeric characters are stripped.- Type: bool
- Default: False
allow_vars
– If True, square brackets are not sanitized, so you can use variables.- Type: bool
- Default: True
Returns:
A sanitized string.
- Type: unicode
function inline_script.set(var, val)
Sets an OpenSesame variable.
If you want to set a variable so that it is available in other items as well (such as the logger item, so you can log the variable), you need to use the set() function from the experiment. So, in an inline_script item you would generally set a variable with exp.set(), rather than self.set().
Important note:
You can only set simple variable types (unicode, float, and int). If you use the set function to save another type of variable, it will be converted to a unicode representation.
Example:
exp.set('my_timestamp', self.time())
Arguments:
var
– The name of an experimental variable.- Type: str, unicode
val
– A value.
function inline_script.set_response(response=None, response_time=None, correct=None)
Processes a response in such a way that feedback variables are updated as well.
Example:
from openexp.keyboard import keyboard
my_keyboard = keyboard(exp)
t1 = self.time()
button, timestamp = my_keyboard.get_key()
if button == 'left':
correct = 1
else:
correct = 0
rt = timestamp - t1
self.set_response(response=button, response_time=rt,
correct=correct)
Keywords:
response
– The response value.- Default: None
response_time
– The response time, or None.- Type: int, float, NoneType
- Default: None
correct
– The correctness value, which should be 0, 1, True, False, or None.- Type: int, bool, NoneType
- Default: None
function inline_script.sleep(ms)
Sleeps for a specified duration.
Example:
self.sleep(1000) # Sleeps one second
Arguments:
ms
– An value specifying the duration in milliseconds.- Type: int, float
function inline_script.time()
Returns a timestamp for the current time. This timestamp only has a relative meaning, i.e. you can use it to determine the interval between two moments, but not the actual time. Whether the timestamp is a float
or int
depends on the back-end.
Example:
print('The time is %s' % self.time())
Returns:
A timestamp of the current time.
- Type: int, float
function inline_script.unistr(val)
Converts a value to a unicode string. This function is mostly necessary to make sure that normal strings with special characters are correctly encoded into unicode, and don’t result in TypeErrors.
The conversion logic is as follows:
- unicode values are returned unchanged.
- str values are decoded using utf-8.
- all other types are typecast to unicode, assuming utf-8 encoding where applicable.
Arguments:
val
– A value of any type.
Returns:
A unicode string.
- Type: unicode
function inline_script.unset(var)
Unsets (forgets) an OpenSesame variable.
Example:
self.set('var', 'Hello world!')
print(self.get('var')) # Prints 'Hello world!'
self.unset('variable_to_forget')
print(self.get('var')) # Gives error!
Arguments:
var
– The name of an OpenSesame variable.- Type: str, unicode
function inline_script.usanitize(s, strict=False)
Converts all non-ASCII characters to U+XXXX notation, so that the resulting string can be treated as plain ASCII text.
Arguments:
s
– A unicode string to be santized- Type: unicode
Keywords:
strict
– If True, special characters are ignored rather than recoded.- Type: bool
- Default: False
Returns:
A regular Python string with all special characters replaced by U+XXXX notation or ignored (if strict).
- Type: str