Managing environment variables

The MacroServer stores variable - value pairs, called environment variables, persistently. Macros use them to share configuration (or even small data) between executions. Sardana built-in macros use a set of standard variables listed in the Environment Variable Catalog, and you can also define your own variables. See Macro Environment for the full description of the environment concept, value types and scopes.

Getting and setting variables

The most common way of accessing the environment is using the environment macros from Spock (or any other macro execution client):

  • lsenv - list environment variables and their values

  • senv - set the value of an environment variable (create it if it does not exist)

  • genv - get the value of an environment variable

  • usenv - unset (remove) one or more environment variables

  • dumpenv - dump the complete environment, including internal variables, e.g. for diagnostics

  • load_env - load environment variables from a file

For example:

Door_demo1_1 [1]: senv ScanDir /tmp/scans
ScanDir = /tmp/scans

Door_demo1_1 [2]: genv ScanDir
ScanDir =
'/tmp/scans'

Door_demo1_1 [3]: usenv ScanDir
Environment variable(s) ScanDir removed

Important

Environment variable names are case sensitive. So, variable Foo is a different variable than foo.

Values are interpreted as Python literals (numbers, strings, lists, dictionaries, …); anything that does not evaluate to a Python literal is treated as a string - see Environment Variables Types.

Door and macro specific variables

By default a variable is set on the global scope: it applies to all doors and all macros. You can restrict a variable to a specific door and/or to a specific macro by prefixing its name with the door device name and/or the macro name, separated by dots:

# only for macros running on door Door/demo1/2
Door_demo1_1 [1]: senv Door/demo1/2.Foo Bar

# only for the ascan macro, on any door
Door_demo1_1 [2]: senv ascan.Foo Bar

# only for the ascan macro when run on door Door/demo1/2
Door_demo1_1 [3]: senv Door/demo1/2.ascan.Foo Bar

Scoped variables override the global ones. Remember to use the Door device name (not its alias) when defining variables on the door scope. The details of the scope resolution are explained in Macro Environment.

Accessing the environment from macros

Inside a macro you can use the getEnv and setEnv API to read and write environment variables:

@macro()
def save_position(self, motor):
    position = motor.getPosition()
    self.setEnv("SavedPosition", position)
    self.output("Saved position: %f", position)

See Accessing Macro Environment for more details and examples.