Python ScriptingΒΆ

Function blocks can be configured to use Python scripting instead of the standard mXparser logic. When Python is selected as the logic engine, a Python script can be entered or pasted into the equation text area.

During execution, the calculation engine automatically injects input pin and parameter values into the script. Output pin values are determined by the results of the script, which must be returned using print statements.

Example:

This example implements a simple equation: c = a + b

The function block Python script is entered as follows:

import sys
c = int(a) + int(b)
print('c=' + str(c))

In this script:

  • a and b are not explicitly assigned within the script. The calculation service prepends these assignments automatically during processing.

  • Output results are returned to the calculation service process through the use of print statements. Each function block output pin value produced by the Python script must be included in a print statement using the format pin=result. For example, use print('pin=' + str(result)), or as shown in the example below: print('c=' + str(c)).

  • It is recommended to use single quotes for string literals.

During processing, the calculation service creates a temporary .py file that includes the script along with the automatically injected input values. For the example above, the temporary file might look like:

c = float('NaN')
a = 24.8
b = 45.3
import sys
c = int(a) + int(b)
print('c=' + str(c))

This temporary file is deleted once execution is complete.

Notes:

  • At present, no additional Python packages (via pip install) are included. A core set of packages will be defined and added in a future release.

  • To log the Python version to the debug log (when debug logging is enabled), include the following lines:

    import platform
    print('PythonVersion - ' + platform.python_version())
    
  • Use a leading # to add comments in the script:

    # This is a comment line