Macro API reference

Macro class

class Macro(*args, **kwargs)[source]

The Macro base class. All macros should inherit directly or indirectly from this class.

Init = 9

internal variable

Running = 10

internal variable

Pause = 7

internal variable

Stop = 7

internal variable

Fault = 8

internal variable

Finished = 0

internal variable

Ready = 0

internal variable

Abort = 0

internal variable

Exception = 11

internal variable

All = 'All'

Constant used to specify all elements in a parameter

BlockStart = '<BLOCK>'

internal variable

BlockFinish = '</BLOCK>'

internal variable

param_def = []

This property holds the macro parameter description. It consists of a sequence of parameter information objects. A parameter information object is either:

  1. a simple parameter object

  2. a parameter repetition object

A simple parameter object is a sequence of:

  1. a string representing the parameter name

  2. a member of Macro.Type representing the parameter data type

  3. a default value for the parameter or None if there is no default value

  4. a string with the parameter description

Example:

param_def = ( ('value', Type.Float, None, 'a float parameter' ) )

A parameter repetition object is a sequence of:

  1. a string representing the parameter repetition name

  2. a sequence of parameter information objects

  3. a dictionary representing the parameter repetition semantics or None to use the default parameter repetition semantics. Dictionary keys are:

    • min - integer representing minimum number of repetitions or None for no minimum.

    • max - integer representing maximum number of repetitions or None for no maximum.

    Default parameter repetition semantics is { 'min': 1, 'max' : None } (in other words, “at least one repetition” semantics)

Example:

param_def = (
    ( 'motor_list', ( ( 'motor', Type.Motor, None, 'motor name') ), None, 'List of motors')
)
result_def = []

This property holds the macro result description. It a single parameter information object.

See also

param_def

hints = {}

Hints to give a client to perform special tasks. Example: scan macros give hints on the types of hooks they support. A GUI can use this information to allow a scan to have sub-macros executed as hooks.

env = ()

a set of mandatory environment variable names without which your macro cannot run

interactive = False

decide if the macro should be able to receive input from the user [default: False]. A macro which asks input but has this flag set to False will print a warning message each time it is executed

run(*args)[source]

Macro API. Runs the macro. Overwrite MANDATORY! Default implementation raises RuntimeError.

Raises:

RuntimeError

prepare(*args, **kwargs)[source]

Macro API. Prepare phase. Overwrite as necessary. Default implementation does nothing

on_abort()[source]

Macro API. Hook executed when an abort occurs. Overwrite as necessary. Default implementation does nothing

on_pause()[source]

Macro API. Hook executed when a pause occurs. Overwrite as necessary. Default implementation does nothing

on_stop()[source]

Macro API. Hook executed when a stop occurs. Overwrite as necessary. Default implementation calls on_abort()

checkPoint()[source]

Macro API. Empty method that just performs a checkpoint. This can be used to check for the stop. Usually you won’t need to call this method

pausePoint(timeout=None)[source]

Macro API. Will establish a pause point where called. If an external source as invoked a pause then, when this this method is called, it will be block until the external source calls resume. You may want to call this method if your macro takes a considerable time to execute and you may whish to pause it at some time. Example:

for i in range(10000):
    time.sleep(0.1)
    self.output("At step %d/10000", i)
    self.pausePoint()
Parameters:

timeout (Optional[float]) – timeout in seconds [default: None, meaning wait forever]

Return type:

Any

property macros

Macro API. An object that contains all macro classes as members. With the returning object you can invoke other macros. Example:

m = self.macros.ascan('th', '0', '90', '10', '2')
scan_data = m.data
getMacroStatus()[source]

Macro API. Returns the current macro status. Macro status is a dict where keys are the strings:

  • id - macro ID (internal usage only)

  • range - the full progress range of a macro (usually a tuple of two numbers (0, 100))

  • state - the current macro state, a string which can have values start, step, stop and abort

  • step - the current step in macro. Should be a value inside the allowed macro range

Return type:

Dict

Returns:

the macro status

getName()[source]

Macro API. Returns this macro name

Return type:

str

Returns:

the macro name

getID()[source]

Macro API. Returns this macro id

Return type:

str

Returns:

the macro id

getParentMacro()[source]

Macro API. Returns the parent macro reference.

Return type:

Macro

Returns:

the parent macro reference or None if there is no parent macro

getDescription()[source]

Macro API. Returns a string description of the macro.

Return type:

str

Returns:

the string description of the macro

getParameters()[source]

Macro API. Returns a the macro parameters. It returns a list containning the parameters with which the macro was executed

Return type:

List

Returns:

the macro parameters

getExecutor()[source]

Macro API. Returns the reference to the object that invoked this macro. Usually is a MacroExecutor object.

Return type:

MacroExecutor

Returns:

the reference to the object that invoked this macro

getDoorObj()[source]

Macro API. Returns the reference to the Door that invoked this macro.

Returns:

the reference to the Door that invoked this macro.

Rype:

Door

getManager()[source]

Macro API. Returns the manager for this macro (usually a MacroServer)

Return type:

MacroServer

Returns:

the MacroServer

property manager: MacroServer

Macro API. Returns the manager for this macro (usually a MacroServer)

Returns:

the MacroServer

getMacroServer()[source]

Macro API. Returns the MacroServer for this macro

Return type:

MacroServer

Returns:

the MacroServer

property macro_server: MacroServer

Macro API. Returns the MacroServer for this macro

Returns:

the MacroServer

getDoorName()[source]

Macro API. Returns the string with the name of the Door that invoked this macro.

Return type:

str

Returns:

the string with the name of the Door that invoked this macro.

getCommand()[source]

Macro API. Returns the string used to execute the macro. Ex.: ‘ascan M1 0 1000 100 0.8’

Return type:

str

Returns:

the macro command.

getMacroCommand()[source]

Macro API. Returns the string used to execute the macro. Ex.: ‘ascan M1 0 1000 100 0.8’

Return type:

str

Returns:

the macro command.

getDateString(time_format='%a %b %d %H:%M:%S %Y')[source]

Macro API. Helper method. Returns the current date in a string.

Parameters:

time_format (str) – the format in which the date should be returned (optional, default value is ‘%a %b %d %H:%M:%S %Y’

Return type:

str

Returns:

the current date

outputDate(time_format='%a %b %d %H:%M:%S %Y')[source]

Macro API. Helper method. Outputs the current date into the output buffer

Parameters:

time_format (str) – (str) the format in which the date should be returned (optional, default value is ‘%a %b %d %H:%M:%S %Y’

Return type:

Any

sendRecordData(data, codec=None)[source]

Macro API. Sends the given data to the RecordData attribute of the Door

Parameters:
  • data (Any) – data to be sent (must be compatible with the codec)

  • codec (Optional[str]) – codec to encode data (in Tango server None defaults to “utf8_json”)

Return type:

Any

plot(*args, **kwargs)[source]

Macro API. Sends the plot command to the client using the ‘RecordData’ DevEncoded attribute. The data is encoded using the pickle -> BZ2 codec.

Parameters:
  • args – the plotting args

  • kwargs – the plotting keyword args

property pylab
property pyplot
getData()[source]

Macro API. Returns the data produced by the macro.

Raises:

Exception if no data has been set before on this macro

Return type:

Any

Returns:

the data produced by the macro

setData(data)[source]

Macro API. Sets the data for this macro

Parameters:

data (object) – new data to be associated with this macro

property data: Any

macro data

print(*args, **kwargs)[source]

Macro API. Prints a message. Accepted args and kwargs are the same as print(). Example:

self.print("this is a print for macro", self.getName())

Note

you will need python >= 3.0. If you have python 2.x then you must include at the top of your file the statement:

from __future__ import print_function
input(msg, *args, **kwargs)[source]

Macro API. If args is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

Depending on which type of application you are running, some of the keywords may have no effect (ex.: spock ignores decimals when a number is asked).

Recognized kwargs:

  • data_type : [default: Type.String] specific input type. Can also specify a sequence of strings with possible values (use allow_multiple=True to say multiple values can be selected)

  • key : [default: no default] variable/label to assign to this input

  • unit: [default: no default] units (useful for GUIs)

  • timeout : [default: None, meaning wait forever for input]

  • default_value : [default: None, meaning no default value] When given, it must be compatible with data_type

  • allow_multiple : [default: False] in case data_type is a sequence of values, allow multiple selection

  • minimum : [default: None] When given, must be compatible with data_type (useful for GUIs)

  • maximum : [default: None] When given, must be compatible with data_type (useful for GUIs)

  • step : [default: None] When given, must be compatible with data_type (useful for GUIs)

  • decimals : [default: None] When given, must be compatible with data_type (useful for GUIs)

Examples:

device_name = self.input("Which device name (%s)?", "tab separated")

point_nb = self.input("How many points?", data_type=Type.Integer)

calc_mode = self.input("Which algorithm?", data_type=["Average", "Integral", "Sum"],
                       default_value="Average", allow_multiple=False)
output(msg, *args, **kwargs)[source]

Macro API. Record a log message in this object’s output. Accepted args and kwargs are the same as logging.Logger.log(). Example:

self.output("this is a print for macro %s", self.getName())
Parameters:
  • msg (str) – the message to be recorded

  • args (Any) – list of arguments

  • kwargs (Any) – list of keyword arguments

Return type:

Any

log(level, msg, *args, **kwargs)[source]

Macro API. Record a log message in this object’s logger. Accepted args and kwargs are the same as logging.Logger.log(). Example:

self.debug(logging.INFO, "this is a info log message for macro %s", self.getName())
Parameters:
  • level (int) – the record level

  • msg (str) – the message to be recorded

  • args (Any) – list of arguments

  • kwargs (Any) – list of keyword arguments

Return type:

Any

debug(msg, *args, **kwargs)[source]

Macro API. Record a debug message in this object’s logger. Accepted args and kwargs are the same as logging.Logger.debug(). Example:

self.debug("this is a log message for macro %s", self.getName())
Parameters:
  • msg (str) – the message to be recorded

  • args (Any) – list of arguments

  • kw – list of keyword arguments

Return type:

Any

info(msg, *args, **kwargs)[source]

Macro API. Record an info message in this object’s logger. Accepted args and kwargs are the same as logging.Logger.info(). Example:

self.info("this is a log message for macro %s", self.getName())
Parameters:
  • msg (str) – the message to be recorded

  • args (Any) – list of arguments

  • kwargs (Any) – list of keyword arguments

Return type:

Any

warning(msg, *args, **kwargs)[source]

Macro API. Record a warning message in this object’s logger. Accepted args and kwargs are the same as logging.Logger.warning(). Example:

self.warning("this is a log message for macro %s", self.getName())
Parameters:
  • msg (str) – the message to be recorded

  • args (Any) – list of arguments

  • kwargs (Any) – list of keyword arguments

Return type:

Any

error(msg, *args, **kwargs)[source]

Macro API. Record an error message in this object’s logger. Accepted args and kwargs are the same as logging.Logger.error(). Example:

self.error("this is a log message for macro %s", self.getName())
Parameters:
  • msg (str) – the message to be recorded

  • args (Any) – list of arguments

  • kwargs (Any) – list of keyword arguments

Return type:

Any

critical(msg, *args, **kwargs)[source]

Macro API. Record a critical message in this object’s logger. Accepted args and kwargs are the same as logging.Logger.critical(). Example:

self.critical("this is a log message for macro %s", self.getName())
Parameters:
  • msg (str) – the message to be recorded

  • args (Any) – list of arguments

  • kwargs (Any) – list of keyword arguments

Return type:

Any

trace(msg, *args, **kwargs)[source]

Macro API. Record a trace message in this object’s logger.

Parameters:
  • msg – (str) the message to be recorded

  • args – list of arguments

  • kw – list of keyword arguments

traceback(*args, **kwargs)[source]

Macro API. Logs the traceback with level TRACE on the macro logger.

stack(*args, **kwargs)[source]

Macro API. Logs the stack with level TRACE on the macro logger.

report(msg, *args, **kwargs)[source]

Macro API. Record a log message in the sardana report (if enabled) with default level INFO. The msg is the message format string, and the args are the arguments which are merged into msg using the string formatting operator. (Note that this means that you can use keywords in the format string, together with a single dictionary argument.)

kwargs are the same as logging.Logger.debug() plus an optional level kwargs which has default value INFO

Example:

self.report("this is an official report of macro %s", self.getName())
Parameters:
  • msg (str) – the message to be recorded

  • args (Any) – list of arguments

  • kwargs (Any) – list of keyword arguments

Return type:

Any

flushOutput()[source]

Macro API. Flushes the output buffer.

getMacroThread()[source]

Macro API. Returns the python thread where this macro is running

Return type:

Thread

Returns:

the python thread where this macro is running

getMacroThreadID()[source]

Macro API. Returns the python thread id where this macro is running

Return type:

int

Returns:

the python thread id where this macro is running

createExecMacroHook(par_str_sequence, parent_macro=None)[source]

Macro API. Creates a hook that executes the macro given as a sequence of strings where the first string is macro name and the following strings the macro parameters

Parameters:
  • par_str_sequence – the macro parameters

  • parent_macro – the parent macro object. If None is given (default) then the parent macro is this macro

Returns:

a ExecMacroHook object (which is a callable object)

createMacro(*pars)[source]

Macro API. Create a new macro and prepare it for execution Several different parameter formats are supported:

# several parameters:
self.createMacro('ascan', 'th', '0', '100', '10', '1.0')
self.createMacro('mv', [[motor.getName(), '0']])
self.createMacro('mv', motor.getName(), '0') # backwards compatibility - see note
self.createMacro('ascan', 'th', 0, 100, 10, 1.0)
self.createMacro('mv', [[motor.getName(), 0]])
self.createMacro('mv', motor.getName(), 0) # backwards compatibility - see note
th = self.getObj('th')
self.createMacro('ascan', th, 0, 100, 10, 1.0)
self.createMacro('mv', [[th, 0]])
self.createMacro('mv', th, 0) # backwards compatibility - see note

# a sequence of parameters:
self.createMacro(['ascan', 'th', '0', '100', '10', '1.0'])
self.createMacro(['mv', [[motor.getName(), '0']]])
self.createMacro(['mv', motor.getName(), '0']) # backwards compatibility - see note
self.createMacro(('ascan', 'th', 0, 100, 10, 1.0))
self.createMacro(['mv', [[motor.getName(), 0]]])
self.createMacro(['mv', motor.getName(), 0]) # backwards compatibility - see note
th = self.getObj('th')
self.createMacro(['ascan', th, 0, 100, 10, 1.0])
self.createMacro(['mv', [[th, 0]]])
self.createMacro(['mv', th, 0]) # backwards compatibility - see note


# a space separated string of parameters (this is not compatible
# with multiple or nested repeat parameters, furthermore the repeat
# parameter must be the last one):
self.createMacro('ascan th 0 100 10 1.0')
self.createMacro('mv %s 0' % motor.getName())

Note

From Sardana 2.0 the repeat parameter values must be passed as lists of items. An item of a repeat parameter containing more than one member is a list. In case when a macro defines only one repeat parameter and it is the last parameter, for the backwards compatibility reasons, the plain list of items’ members is allowed.

Parameters:

pars (Any) – the command parameters as explained above

Return type:

Tuple[Macro, Sequence[Any]]

Returns:

a sequence of two elements: the macro object and the result of preparing the macro

prepareMacroObj(macro_name_or_klass, *args, **kwargs)[source]

Macro API. Prepare a new macro for execution

Parameters:
  • name (macro_name_or_klass) – name of the macro to be prepared or the macro class itself

  • pars – list of parameter objects

  • init_opts – keyword parameters for the macro constructor

  • prepare_opts – keyword parameters for the macro prepare

Returns:

a sequence of two elements: the macro object and the result of preparing the macro

prepareMacro(*args, **kwargs)[source]

Macro API. Prepare a new macro for execution Several different parameter formats are supported:

# several parameters:
self.prepareMacro('ascan', 'th', '0', '100', '10', '1.0')
self.prepareMacro('mv', [[motor.getName(), '0']])
self.prepareMacro('mv', motor.getName(), '0') # backwards compatibility - see note
self.prepareMacro('ascan', 'th', 0, 100, 10, 1.0)
self.prepareMacro('mv', [[motor.getName(), 0]])
self.prepareMacro('mv', motor.getName(), 0) # backwards compatibility - see note
th = self.getObj('th')
self.prepareMacro('ascan', th, 0, 100, 10, 1.0)
self.prepareMacro('mv', [[th, 0]])
self.prepareMacro('mv', th, 0) # backwards compatibility - see note

# a sequence of parameters:
self.prepareMacro(['ascan', 'th', '0', '100', '10', '1.0'])
self.prepareMacro(['mv', [[motor.getName(), '0']]])
self.prepareMacro(['mv', motor.getName(), '0']) # backwards compatibility - see note
self.prepareMacro(('ascan', 'th', 0, 100, 10, 1.0))
self.prepareMacro(['mv', [[motor.getName(), 0]]])
self.prepareMacro(['mv', motor.getName(), 0]) # backwards compatibility - see note
th = self.getObj('th')
self.prepareMacro(['ascan', th, 0, 100, 10, 1.0])
self.prepareMacro(['mv', [[th, 0]]])
self.prepareMacro(['mv', th, 0]) # backwards compatibility - see note

# a space separated string of parameters (this is not compatible
# with multiple or nested repeat parameters, furthermore the repeat
# parameter must be the last one):
self.prepareMacro('ascan th 0 100 10 1.0')
self.prepareMacro('mv %s 0' % motor.getName())

Note

From Sardana 2.0 the repeat parameter values must be passed as lists of items. An item of a repeat parameter containing more than one member is a list. In case when a macro defines only one repeat parameter and it is the last parameter, for the backwards compatibility reasons, the plain list of items’ members is allowed.

Parameters:
  • args – the command parameters as explained above

  • kwargs – keyword optional parameters for prepare

Returns:

a sequence of two elements: the macro object and the result of preparing the macro

runMacro(*args, **kwargs)[source]

Macro API. Runs the macro with predefined macro object or list of arguments representing the macro and returns the result of macro execution after the macro is completed or an exception is thrown.

In case of some operation needs to be done between the macro preparation and the macro execution use macro object as first argument.

Passing list of arguments representing the macro implicitly prepares the macro before running it. Examples:

macro = self.prepareMacro("mymacro", "myparam")
self.do_my_stuff_with_macro(macro)
self.runMacro(macro)

# pass arguments as in :meth:`~sardana.macroserver.macro.Macro.execMacro`
self.runMacro(["mymacro", "myparam"])
# or
self.runMacro("mymacro", "myparam")
Parameters:

args – macro object or parameters as explained in execMacro()

Returns:

macro result

execMacroObj(name, *args, **kwargs)[source]

Macro API. Execute a macro in this macro. The method only returns after the macro is completed or an exception is thrown. This is a higher level version of runMacro method. It is the same as:

macro = self.prepareMacroObjs(name, *args, **kwargs)
self.runMacro(macro)
return macro
Parameters:
  • name (str) – name of the macro to be prepared

  • args (Any) – list of parameter objects

  • kwargs (Any) – list of keyword parameters

Return type:

Macro

Returns:

a macro object

execMacro(*args, **kwargs)[source]

Macro API. Execute a macro in this macro. The method only returns after the macro is completed or an exception is thrown. Several different parameter formats are supported:

# several parameters:
self.execMacro('ascan', 'th', '0', '100', '10', '1.0')
self.execMacro('mv', [[motor.getName(), '0']])
self.execMacro('mv', motor.getName(), '0') # backwards compatibility - see note
self.execMacro('ascan', 'th', 0, 100, 10, 1.0)
self.execMacro('mv', [[motor.getName(), 0]])
self.execMacro('mv', motor.getName(), 0) # backwards compatibility - see note
th = self.getObj('th')
self.execMacro('ascan', th, 0, 100, 10, 1.0)
self.execMacro('mv', [th, 0]])
self.execMacro('mv', th, 0) # backwards compatibility - see note

# a sequence of parameters:
self.execMacro(['ascan', 'th', '0', '100', '10', '1.0')
self.execMacro(['mv', [[motor.getName(), '0']]])
self.execMacro(['mv', motor.getName(), '0']) # backwards compatibility - see note
self.execMacro(('ascan', 'th', 0, 100, 10, 1.0))
self.execMacro(['mv', [[motor.getName(), 0]]])
self.execMacro(['mv', motor.getName(), 0]) # backwards compatibility - see note
th = self.getObj('th')
self.execMacro(['ascan', th, 0, 100, 10, 1.0])
self.execMacro(['mv', [[th, 0]]])
self.execMacro(['mv', th, 0]) # backwards compatibility - see note

# a space separated string of parameters (this is not compatible
# with multiple or nested repeat parameters, furthermore the repeat
# parameter must be the last one):
self.execMacro('ascan th 0 100 10 1.0')
self.execMacro('mv %s 0' % motor.getName())

Note

From Sardana 2.0 the repeat parameter values must be passed as lists of items. An item of a repeat parameter containing more than one member is a list. In case when a macro defines only one repeat parameter and it is the last parameter, for the backwards compatibility reasons, the plain list of items’ members is allowed.

Parameters:

pars – the command parameters as explained above

Returns:

a macro object

getTangoFactory()[source]

Macro API. Helper method that returns the tango factory.

Return type:

TangoFactory

Returns:

the tango factory singleton

getDevice(dev_name)[source]

Macro API. Helper method that returns the device for the given device name

Return type:

TaurusDevice

Returns:

the taurus device for the given device name

setLogBlockStart()[source]

Macro API. Specifies the begining of a block of data. Basically it outputs the ‘BLOCK’ tag

setLogBlockFinish()[source]

Macro API. Specifies the end of a block of data. Basically it outputs the ‘/BLOCK’ tag

outputBlock(line)[source]

Macro API. Sends an line tagged as a block to the output

Parameters:

line (str) – line to be sent

getPools()[source]

Macro API. Returns the list of known device pools.

Return type:

Sequence[Pool]

Returns:

the list of known device pools

addObj(obj, priority=0)[source]

Macro API. Adds the given object to the list of controlled objects of this macro. In practice it means that if a stop is executed the stop method of the given object will be called.

Parameters:
  • obj (object) – the object to be controlled

  • priority (int) – wheater or not reserve with priority [default: 0 meaning no priority ]

Return type:

Any

addObjs(obj_list)[source]

Macro API. Adds the given objects to the list of controlled objects of this macro. In practice it means that if a stop is executed the stop method of the given object will be called.

Parameters:

obj_list (Sequence[Any]) – list of objects to be controlled

Return type:

Any

returnObj(obj)[source]

Removes the given objects to the list of controlled objects of this macro.

Parameters:

obj (Any) – object to be released from the control

Return type:

object

getObj(name, type_class='All', subtype='All', pool='All', reserve=True)[source]

Macro API. Gets the object of the given type belonging to the given pool with the given name. The object (if found) will automatically become controlled by the macro.

Raises:

MacroWrongParameterType if name is not a string

Raises:

AttributeError if more than one matching object is found

Parameters:
  • name (str) – string representing the name of the object. Can be a regular expression

  • type_class (Any) – the type of object [default: All]

  • subtype (Any) – a string representing the subtype [default: All] Ex.: if type_class is Type.ExpChannel, subtype could be ‘CTExpChannel’

  • pool (Any) – the pool to which the object should belong [default: All]

  • reserve (Any) – automatically reserve the object for this macro [default: True]

Return type:

Any

Returns:

the object or None if no compatible object is found

getObjs(names, type_class='All', subtype='All', pool='All', reserve=True)[source]

Macro API. Gets the objects of the given type belonging to the given pool with the given names. The objects (if found) will automatically become controlled by the macro.

Parameters:
  • names – a string or a sequence of strings representing the names of the objects. Each string can be a regular expression

  • type_class – the type of object (optional, default is All). Example: Type.Motor, Type.ExpChannel

  • subtype – a string representing the subtype (optional, default is All) Ex.: if type_class is Type.ExpChannel, subtype could be ‘CTExpChannel’

  • pool – the pool to which the object should belong (optional, default is All)

  • reserve – automatically reserve the object for this macro (optional, default is True)

Returns:

a list of objects or empty list if no compatible object is found

findObjs(names, type_class='All', subtype='All', pool='All', reserve=True)[source]

Macro API. Gets the objects of the given type belonging to the given pool with the given names. The objects (if found) will automatically become controlled by the macro.

Parameters:
  • names – a string or a sequence of strings representing the names of the objects. Each string can be a regular expression

  • type_class – the type of object (optional, default is All)

  • subtype – a string representing the subtype [default: All] Ex.: if type_class is Type.ExpChannel, subtype could be ‘CTExpChannel’

  • pool – the pool to which the object should belong [default: All]

  • reserve – automatically reserve the object for this macro [default: True]

Returns:

a list of objects or empty list if no compatible object is found

getMacroNames()[source]

Macro API. Returns a list of strings containing the names of all known macros :rtype: Sequence[str]

return:

a sequence of macro names

getMacros(filter=None)[source]

Macro API. Returns a sequence of MacroClass /MacroFunction objects for all known macros that obey the filter expression.

Parameters:

filter (Optional[str]) – a regular expression for the macro name (optional, default is None meaning match all macros)

Return type:

Sequence[Union[MacroClass, MacroFunction]]

Returns:

a sequence of MacroClass /MacroFunction objects

getMacroLibraries(filter=None)[source]

Macro API. Returns a sequence of MacroLibrary objects for all known macros that obey the filter expression.

Parameters:

filter (Optional[str]) – a regular expression for the macro library [default: None meaning match all macro libraries)

Return type:

Sequence[MacroLibrary]

Returns:

a sequence of MacroLibrary objects

getMacroLibrary(lib_name)[source]

Macro API. Returns a MacroLibrary object for the given library name.

Parameters:

lib_name (str) – library name

Return type:

MacroLibrary

Returns:

a macro library MacroLibrary

getMacroLib(lib_name)

Macro API. Returns a MacroLibrary object for the given library name.

Parameters:

lib_name (str) – library name

Return type:

MacroLibrary

Returns:

a macro library MacroLibrary

getMacroLibs(filter=None)

Macro API. Returns a sequence of MacroLibrary objects for all known macros that obey the filter expression.

Parameters:

filter (Optional[str]) – a regular expression for the macro library [default: None meaning match all macro libraries)

Return type:

Sequence[MacroLibrary]

Returns:

a sequence of MacroLibrary objects

getMacroInfo(macro_name)[source]

Macro API. Returns the corresponding MacroClass /MacroFunction object.

Parameters:

macro_name (str) – a string with the desired macro name.

Return type:

Union[MacroClass, MacroFunction]

Returns:

a MacroClass /MacroFunction object or None if the macro with the given name was not found

getMotion(elems, motion_source=None, read_only=False, cache=True)[source]

Macro API. Returns a new Motion object containing the given elements.

Raises:

Exception if no elements are defined or the elems is not recognized as valid, or an element is not found or an element appears more than once

Parameters:
  • elems – list of moveable object names

  • motion_source – obj or list of objects containing moveable elements. Usually this is a Pool object or a list of Pool objects (optional, default is None, meaning all known pools will be searched for the given moveable items

  • read_only – not used. Reserved for future use

  • cache – not used. Reserved for future use

Returns:

a Motion object

getElementsWithInterface(interface)[source]
getControllers()[source]
getMoveables()[source]
getMotors()[source]
getPseudoMotors()[source]
getIORegisters()[source]
getMeasurementGroups()[source]
getExpChannels()[source]
getCounterTimers()[source]
get0DExpChannels()[source]
get1DExpChannels()[source]
get2DExpChannels()[source]
getPseudoCounters()[source]
getInstruments()[source]
getElementWithInterface(interface, name)[source]
getController(name)[source]
getMoveable(name)[source]
getMotor(name)[source]
getPseudoMotor(name)[source]
getIORegister(name)[source]
getMeasurementGroup(name)[source]
getExpChannel(name)[source]
getCounterTimer(name)[source]
get0DExpChannel(name)[source]
get1DExpChannel(name)[source]
get2DExpChannel(name)[source]
getPseudoCounter(name)[source]
getInstrument(name)[source]
getEnv(key=None, macro_name=None, door_name=None)[source]

Macro API. Gets the local environment matching the given parameters:

  • door_name and macro_name define the context where to look for the environment. If both are None, the global environment is used. If door name is None but macro name not, the given macro environment is used and so on…

  • If key is None it returns the complete environment, otherwise key must be a string containing the environment variable name.

Raises:

UnknownEnv

Parameters:
  • key (Optional[str]) – environment variable name [default: None, meaning all environment]

  • door_name (Optional[str]) – local context for a given door [default: None, meaning no door context is used]

  • macro_name (Optional[str]) – local context for a given macro [default: None, meaning no macro context is used]

Return type:

Dict

Returns:

a dict containing the environment

getGlobalEnv()[source]

Macro API. Returns the global environment.

Return type:

Dict

Returns:

a dict containing the global environment

getAllEnv()[source]

Macro API. Returns the enviroment for the macro.

Return type:

Dict

Returns:

a dict containing the environment for the macro

getAllDoorEnv()[source]

Macro API. Returns the enviroment for the door where the macro is running.

Return type:

Dict

Returns:

a dict containing the environment

setEnv(key, value)[source]

Macro API. Sets the environment key to the new value and stores it persistently.

Return type:

Tuple[str, Any]

Returns:

a tuple with the key and value objects stored

unsetEnv(key)[source]

Macro API. Unsets the given environment variable.

Parameters:

key (str) – the environment variable name

Return type:

Any

reloadLibrary(lib_name)[source]

Macro API. Reloads the given library(=module) names

Raises:

ImportError in case the library does not exist

Parameters:

lib_name (str) – library(=module) name

Return type:

Any

Returns:

the reloaded python module object

reloadMacro(macro_name)[source]

Macro API. Reloads the module corresponding to the given macro name

Raises:

MacroServerExceptionList in case the macro is unknown or the reload process is not successfull

Parameters:

macro_name (str) – macro name

Return type:

Any

reloadMacros(macro_names)[source]

Macro API. Reloads the modules corresponding to the given macro names.

Raises:

MacroServerExceptionList in case the macro(s) are unknown or the reload process is not successfull

Parameters:

macro_names (Sequence[str]) – a list of macro names

Return type:

None

reloadMacroLibrary(lib_name)[source]

Macro API. Reloads the given library(=module) names

Raises:

MacroServerExceptionList in case the reload process is not successfull

Parameters:

lib_name (str) – library(=module) name

Return type:

MacroLibrary

Returns:

the MacroLibrary for the reloaded library

reloadMacroLibraries(lib_names)[source]

Macro API. Reloads the given library(=module) names

Raises:

MacroServerExceptionList in case the reload process is not successfull for at least one lib

param lib_names: a list of library(=module) names

Return type:

Sequence[MacroLibrary]

Returns:

a sequence of MacroLibrary objects for the reloaded libraries

reloadMacroLib(lib_name)

Macro API. Reloads the given library(=module) names

Raises:

MacroServerExceptionList in case the reload process is not successfull

Parameters:

lib_name (str) – library(=module) name

Return type:

MacroLibrary

Returns:

the MacroLibrary for the reloaded library

reloadMacroLibs(lib_names)

Macro API. Reloads the given library(=module) names

Raises:

MacroServerExceptionList in case the reload process is not successfull for at least one lib

param lib_names: a list of library(=module) names

Return type:

Sequence[MacroLibrary]

Returns:

a sequence of MacroLibrary objects for the reloaded libraries

getViewOption(name)[source]
getViewOptions()[source]
setViewOption(name, value)[source]
resetViewOption(name)[source]
property executor

Unofficial Macro API. Alternative to getExecutor() that does not throw StopException in case of a Stop. This should be called only internally

property door

Unofficial Macro API. Alternative to getDoorObj() that does not throw StopException in case of a Stop. This should be called only internally

property parent_macro

Unofficial Macro API. Alternative to getParentMacro that does not throw StopException in case of a Stop. This should be called only internally by the Executor

property macro_command

Unofficial Macro API. Alternative to getMacroCommand that does not throw StopException in case of a Stop.

property description

Unofficial Macro API. Alternative to getDescription() that does not throw StopException in case of a Stop. This should be called only internally by the Executor

isAborted()[source]

Unofficial Macro API.

isStopped()[source]

Unofficial Macro API.

isPaused()[source]

Unofficial Macro API.

isAnyAncestorStopped()[source]
isAnyAncestorExecutingOnStop()[source]
hasResult()[source]

Unofficial Macro API. Returns True if the macro should return a result or False otherwise

Return type:

bool

Returns:

True if the macro should return a result or False otherwise

getResult()[source]

Unofficial Macro API. Returns the macro result object (if any)

Returns:

the macro result object or None

setResult(result)[source]

Unofficial Macro API. Sets the result of this macro

Parameters:

result – (object) the result for this macro

exec_()[source]

Internal method. Execute macro as an iterator

stop()[source]

Internal method. Activates the stop flag on this macro.

abort()[source]

Internal method. Aborts the macro abruptly.

setProcessingStop(yesno)[source]

Internal method. Activates the processing stop flag on this macro

isProcessingStop()[source]

Internal method. Checks if this macro is processing stop

pause(cb=None)[source]

Internal method. Pauses the macro execution. To be called by the Door running the macro to pause the current macro

resume(cb=None)[source]

Internal method. Resumes the macro execution. To be called by the Door running the macro to resume the current macro

Hookable class

class Hookable(name='', parent=None, format=None)[source]
getAllowedHookHints()[source]
getHints()[source]
getHooks(hint=None)[source]

This will return a list of hooks that have the given hint. Two reserved hints are always valid:

  • “_ALL_”: which contains all the hooks

  • “_NOHINTS_”: which contains the hooks that don’t provide any hint

Parameters:

hint – (str) a hint. If None is passed, it returns a list of (hook,hints) tuples

Returns:

(list) an ordered list of hooks that have the given hint

appendHook(hook_info)[source]

Append a hook according to the hook information

Parameters:

hook_info – sequence of two elements, the first one is the hook and its optional parameters/arguments, the second one is the list of hints e.g. hook places

property hooks

Hooks (callables) attached to the macro object together with the hook places (places where they will be called).

Getter:

Return all hooks attached to the macro object (including general hooks).

Setter:

Set hooks to the object. This may override eventual general hooks. Use appendHook() if the general hooks want to be kept. For backwards compatibility accepts hook in the list<callable> format.

Type:

list<tuple> where each tuple has two elements: callable and list<str>

iMacro class

class iMacro(*args, **kwargs)[source]
interactive = True

decide if the macro should be able to receive input from the user [default: False]. A macro which asks input but has this flag set to False will print a warning message each time it is executed

macro decorator

class macro(param_def=None, result_def=None, env=None, hints=None, interactive=None)[source]

Class designed to decorate a python function to transform it into a macro. Examples:

@macro()
def my_macro1(self):
    self.output("Executing %s", self.getName())

@macro([ ["moveable", Type.Moveable, None, "motor to watch"] ])
def where_moveable(self, moveable):
    self.output("Moveable %s is at %s", moveable.getName(), moveable.getPosition())
param_def = []
result_def = []
env = ()
hints = {}
interactive = False

imacro decorator

imacro

alias of functools.partial(<class ‘sardana.macroserver.macro.macro’>, interactive=True)

StopException

class StopException[source]

AbortException

class AbortException[source]

InterruptException

class InterruptException[source]