Scripts

Getting Started

The typical use case for Labtronyx is as a library that can be imported and used to introduce automation capability with external instruments. There are many cases, however, where automation with external instruments is the primary goal of a Python script. For these cases, Labtronyx provides a Script class that handles much of the boiler-plate operations needed to establish communication with an instrument.

Labtronyx scripts are objects that run commands sequentially from start to completion with an expected outcome. At the end of a script, a PASS or FAIL designation is returned depending on pre-programmed conditions within the script. Any class that subclasses the ScriptBase class has access to a number of convenience functions to ease interaction with external instruments or devices through the Labtronyx framework.

To create a Labtronyx script, all you need is a class that extends ScriptBase and some code that instructs the Labtronyx library to run the script:

import labtronyx

class TestScript(labtronyx.ScriptBase):

    def run(self):
        pass

if __name__ == '__main__':
    labtronyx.runScriptMain()

To run this simple script, just execute the Python file from the command line.

Script Attributes

Attributes provide additional information to Labtronyx about the script that can be used to catalog and identify scripts in a large repository. It is recommended that scripts define these attributes:

  • author
  • version
  • name
  • description
  • continueOnFail
  • allowedFailures

Declaring Required Resources

Labtronyx is fundamentally an automation framework for instruments. Scripts that subclass ScriptBase can declare required resources by defining class attributes that instantiate the RequiredResource class.:

import labtronyx
from labtronyx.script import ScriptBase, RequiredResource

class TestScript(ScriptBase):
    dut = RequiredResource(deviceVendor='Test', deviceModel='Widget')

    def run(self):
        pass

if __name__ == '__main__':
    labtronyx.runScriptMain()

The parameters for RequiredResource are the same parameters passed to InstrumentManager.findResources(). These parameters are matched against the key-value pairs returned by getProperties(). If the parameters are not specific enough, Labtronyx may not be able to resolve the RequiredResource attribute to one resource and cause the script to FAIL because each required resource must resolve to exactly one resource. Resources can be force-resolved by calling assignResource() with the attribute name and a UUID.

Parameters

Scripts can specify parameters that must be provided when the script is opened by defining class attributes that instantiate the ScriptParameter class.:

import labtronyx
from labtronyx.script import ScriptBase, RequiredResource

class TestScript(ScriptBase):
    param = ScriptParameter(attrType=str, required=False, defaultValue='Test')

    def run(self):
        pass

if __name__ == '__main__':
    labtronyx.runScriptMain()

Script parameters are instantiated with the following parameters:

  • attrType - Python class type
  • required - True if the parameter is required, if False defaultValue can be specified
  • defaultValue - Attribute value if not provided when the script is instantiated

Running Scripts

Labtronyx has a helper method that can be used to facilitate script execution from the command line:

if __name__ == '__main__':
    labtronyx.runScriptMain()

Any file that contains exactly one subclass of ScriptBase with that code snippet can be run from the command line. Alternatively, the script can be instantiated and run by calling the start method:

ts = TestScript()
result = ts.start()
print "Script Result: " + result.result

Script Results

The default outcome or result of a script is a PASS designation. The developer is responsible for deciding when to return a FAILURE. FAILURES can be set explicitly by calling the fail method, or by using on of the convenience functions to FAIL on a certain condition. If the continueOnFail attribute is set, a FAILURE will not stop script execution, but the outcome of the script will be reported as FAIL. If script execution needs to be stopped on a FAILURE condition, the stop parameter of the fail method can be set, or any of the convenience functions beginning with assert will cause execution to halt when the condition is met.

class labtronyx.bases.script.ScriptBase(manager, **kwargs)[source]

Script base class, modeled after the Python unittest framework.

Parameters:
assignResource(res_attribute, res_uuid)[source]

Assign a resource with a given uuid to the script attribute res_attribute. Used if a resource could not be resolved to a single resource.

Parameters:
  • res_attribute – Script attribute name
  • res_uuid – Resource UUID
Raises:

KeyError if res_attribute is not a valid RequiredResource attribute

Raises:

ResourceUnavailable if res_uuid is not a valid resource

createFileLogHandler(filename=None)[source]

Create a file log handler to store script logs. Called automatically by the default setUp() method if logToFile is True. Removes any existing file log handlers.

Parameters:filename (str) – filename of new log file
fail(reason, stop=False)[source]

Set the script result to FAIL. Execution will halt on the following conditions:

  • continueOnFail attribute is False
  • allowedFailures attribute has been exceeded
  • stop parameter is True
Parameters:
  • reason (str) – Reason for script failure
  • stop (bool) – Flag to stop script execution
classmethod getClassAttributes()[source]

Get a dictionary of all class attributes

Return type:dict{str: object}
getLog()[source]

Get the last 100 log entries

Returns:list
classmethod getParameterInfo()[source]

Get information about ScriptParameter objects.

Return type:dict{str: dict}
getParameters()[source]

Get script instance parameters

Return type:dict{str: object}
getProperties()[source]

Get script instance properties

Return type:dict{str: object}
classmethod getResourceInfo()[source]

Get information about RequiredResource objects.

Return type:dict{str: dict}
getResourceResolutionInfo()[source]

Get RequiredResource resolution information. Returns a dict with the attribute names as the keys and a list of resolve Resource UUIDs as the value.

Return type:dict{str: list}
isReady()[source]

Check if a script is ready to run. In order to run, a script must meet the following conditions:

  • All resource dependencies must be resolved.
Returns:True if ready, False if not ready
Return type:bool
isRunning()[source]

Check if the script is currently running.

Return type:bool
join(timeout=None)[source]

Wait until the script thread has completed and is no longer alive.

Parameters:timeout (float) – timeout before returning
onException(e)[source]

Method called when an unhandled exception is caught. Default behavior is to log the exception and FAIL the script. When called, script execution has already halted, there is no way to continue execution.

This method can be overriden to change the behavior.

Parameters:e (Exception) – Exception caught
onFail()[source]

Method called when a script is halted due to a FAIL condition. Called after onException (if applicable) but before tearDown. Default behavior is to do nothing.

This method can be overriden to change the behavior.

onPass()[source]

Method called when a script execution has finished with a PASS status. Default behavior is to do nothing.

This method can be overriden to change the behavior.

onSkip()[source]

Method called when a script is halted due to a SKIP condition. Default behavior is to do nothing.

This method can be overriden to change the behavior.

resolveResources()[source]

Attempt to resolve all resource dependencies by iterating through all RequiredResource attributes and finding matching resource objects

run()[source]

Main script body, override this method in script subclasses to put all code. Any exceptions raised will be handled and may cause script FAILURE (depending on behavior of onException).

setProgress(new_progress)[source]

Optional method to set the progress of a script. Useful for external tools or GUIs to report script progress.

Parameters:new_progress (int) – Progress (out of 100)
setStatus(new_status)[source]

Optional method to set the text status of the script. Useful for external tools or GUIs to report script status. Use in conjunction with setProgress

Parameters:new_status (str) – Status
setUp()[source]

Method called to prepare the script for execution. setUp is called immediately before run. Any exception raised will cause script FAILURE and the run method will not be called.

Default behavior is to validate all RequiredResource and ScriptParameter objects and FAIL script if resources could not be resolved or required parameters were not found.

This method can be overriden to change the behavior.

skip(reason)[source]

Set the script result to SKIP and halt execution.

Parameters:reason (str) – Reason for script failure
start()[source]

Script run routine to be called when executing the script. Returns the script result as a ScriptResult object. run is protected from multiple thread execution using a lock.

Return type:ScriptResult
stop()[source]

Stop a script that is running.

Returns:True if script was stopped
Return type:bool
tearDown()[source]

Method called after run has been called and after onPass, onSkip or onFail have been called, depending on the result of the script.

Default behavior is to log script completion information like script result, failure reason, execution time, etc.

This method can be overriden to change the behavior.