VeloX Docs

Python plugins

Python Script 3

Process, transform, or send migration data with your own Python 3 code.

The Python Script 3 plugin runs your own Python 3 code during the migration. Use it to transform data, call third-party systems, or load data into targets that have no dedicated plugin.

You find the plugin in the Non-SAP Targets group of the designer. It works as a target: map a source to its import fields. You can also map its export fields to another plugin.

This page describes the Python 3 version. For the Python 2 version, see Python 2 Script.

Python 3 compared to Python 2

You don't need to install Python. The plugin uses IronPython 3.4, a Python 3 implementation for .NET that ships with VeloXm. Python 3 syntax, such as f-strings, works in your scripts.

Topic Python 2 Script Python 3 Script
Runtime IronPython 2 IronPython 3.4
Entry point Class PyClass with method dowork Function main(kwargs)
Input data JSON string in kwargs['data'] Python dict in kwargs['data']
Return value JSON string Python dict with data and metadata keys
Password Manager clr.AddReference('VeloX.Core') and PasswordManager.GetCredentials(...) kwargs['pm'].get(...)
Debugging Not available Built-in debugger with breakpoints
Editor Check button Check Syntax, Check & Debug, a function list, code folding, search and replace, and a minimap
Run after the project stops Not available Call script after project stopped

Scripts written for Python 2 don't run unchanged. Rewrite the entry point as main(kwargs), read the data as a dictionary, and return a dictionary.

The plugin looks for Python modules in the IronPython3 and IronPython3\pmodules folders of the VeloXm installation, and in the template folder when the plugin is created from a template. Pure Python modules that are compatible with IronPython 3 can be placed there. Modules that depend on CPython C extensions don't work in IronPython.

Runtime details

  • The engine is IronPython 3.4.0. It runs inside the VeloXm process on .NET Framework 4.8. No CPython installation is used, and .NET assemblies can be loaded with import clr.
  • Imports are searched in this order: IronPython3\pmodules, IronPython3, then the template folder.
  • The VeloXm installer unpacks the Python standard library into IronPython3\pmodules. It is the Python 3.4 standard library: modules added in later Python versions, such as typing, dataclasses or secrets, are not included.
  • No third-party packages are bundled for Python 3. The packages that ship with Python 2 (for example requests and openpyxl, see Python Script 2) are not available to Python 3 scripts. Copy pure-Python packages that work with IronPython 3 to IronPython3\pmodules, or attach them to a template.

Settings

Open Settings on the plugin to see these tabs.

General

Setting Description
Description Short description that is shown as the plugin name on the canvas.
Editor Opens the Python script editor.
Notes Opens your notes for the plugin.
Call script after project stopped Runs the After Stop script when the migration finishes.
Use Smart Fields Creator Adds settings fields that call the Structure script to build the plugin structure. See Smart Fields Creator.

Transformations

Select Use Data Transformation to define transformation rules without code. Click Rules to open the rules window. The number of rules is shown below the button. The rules script is passed to your main script as kwargs['rules_script'].

Debug

Select Use Debugger and choose which scripts open in the debugger:

  • Main Script
  • Structure Creation Script
  • Migration Completed Script

See Debugging.

Template

Click Create Template to save the plugin as a reusable template, or Update Template to update an existing one. See Create a plugin template.

Script editor

Click Editor to open the editor. It has three tabs:

  • Main Script runs during the migration.
  • Structure builds the plugin fields. It is available when Use Smart Fields Creator is on.
  • After Stop runs after the migration when Call script after project stopped is on.

Use these buttons:

  • Blank clears the current script.
  • Open loads a script from a file.
  • Save saves the current script to a file.
  • Check Syntax checks the script for errors.
  • Check & Debug checks the script and opens it in the debugger.
  • Apply saves your changes to the plugin. Cancel discards them.

The editor also offers syntax highlighting, code completion, code folding, a list of classes and functions for quick navigation, search and replace, and a minimap. Press Ctrl+/ to comment the selected lines and Ctrl+Shift+/ to uncomment them.

Check Syntax runs the module-level code of the script (imports, definitions and other top-level statements) but doesn't call main. Keep top-level code free of side effects.

Fields

Add fields in the Fields section, on the Import and Export tabs. Enter a name and click Add or press Enter. You can also create fields with the Smart Fields Creator.

The available data types are:

  • String
  • Int
  • Float
  • Structure, which is a Python dict. It can contain String, Int, and Float fields.
  • Table, which is a Python list of dict. It can contain String, Int, and Float fields.

To change the data type, click the field and select a type in Data Type.

Click an import field to set its default value options:

  • No Default Value
  • Ignore Source. uses the default value and ignores the source value.
  • Only If Source Empty. uses the default value only if the source value is empty.

The D flag shows that a default value is used. Select Convert To Upper Case on a field to convert its value to upper case. The U flag appears on the field.

Main script

The main script must define the function main(kwargs). VeloXm calls it once per migration item.

def main(kwargs):
    data = kwargs['data']

    metadata = {
        'status': 's',
        'messages': [
            {
                'header': 'Header message',
                'details': 'Details message'
            }
        ]
    }
    return {'data': data, 'metadata': metadata}

Keyword arguments

Key Description
data Import data as a dict. Simple fields are values, structures are dict, and tables are list of dict.
settings Smart field settings as a dict of name and value.
structure Plugin fields as a dict with input_fields and output_fields.
environment Template folder path, or None.
rules_script Transformation rules script, or None if transformation rules are not used. Run it with exec(kwargs['rules_script']), then return jobj_out.
simulate True when the migration runs in simulation mode.
id Plugin ID.
description Plugin description.
version Plugin version.
pm Password Manager helper. See Password Manager.
ev Environment variables helper. See Environment variables.
log Logger. log.Write(obj) writes the object to the technical log. log.Write(obj, True) writes it to the log header.

Return value

Return a dict with these keys:

  • data: export data as a dict. Keys are export field names. Values can be strings, numbers, booleans, dict for structures, and list of dict for tables.
  • metadata: the transaction status, with these keys:
    • status: s for successful, e for error, or w for warning.
    • messages: a list of messages for the migration log. Each message has header, details, and an optional number.

If status is e, the migration item is marked as an error and the messages are shown as errors. If the script returns something other than a dict, the item fails with the message "Returned object format is not supported."

Only e changes the result: with s, w or no metadata, the item is successful and the messages are added to the log row. Values in data are read by export field name, and field names are case-sensitive. Export fields that are missing from data stay empty.

Run-time behavior

  • When you click Analyze, the plugin compiles the main script and runs its module-level code. Syntax errors and exceptions are shown in a message box, and the run can't start until you fix them.
  • The loaded script is reused for every item of the run, and main(kwargs) is called once per item. Module-level variables keep their values between items, so you can, for example, open a connection once and reuse it. The script is unloaded when the migration completes.
  • With a multithreading parameter above 1, main is called from several threads at the same time in the same module. IronPython has no global interpreter lock, so protect shared state, for example with threading.Lock.
  • If an unhandled exception occurs, the item gets the Error status with the message Exception, and the Python traceback is shown as the detail and written to the technical log.
  • In simulation mode the script runs as usual with simulate set to True. The plugin doesn't skip anything by itself, so check the flag before you write to external systems.

Import values are converted by field type: Int to a 64-bit integer and Float to a float (a dot is the decimal separator). A mapped value that can't be converted is passed as None. A field that is not mapped and has no default value is passed as 0 (Int), 0.0 (Float) or None (String).

Password Manager

Use kwargs['pm'] to read credentials saved in the Password Manager.

pm = kwargs['pm']
cred = pm.get('MY_CONNECTION')        # returns None if the entry doesn't exist
if cred:
    user = cred.User
    password = cred.Password
    host = cred.get_option('HOST', '')  # option value, or the default

Environment variables

Use kwargs['ev'] to store and read values that you share between plugins and runs.

Method Description
get(environment, key) Returns the value.
get(environment, key, default) Returns the value, or default if the environment or key doesn't exist.
get(environment) / set(environment) Returns (or creates) the environment as an object with its own get(key), set(key, value) and remove(key) methods. get returns None if the environment doesn't exist.
set(environment, key, value) Stores the value.
remove(environment, key) Removes the key.
remove_env(environment) Removes the whole environment.

Smart Fields Creator

The Smart Fields Creator adds settings fields to the plugin. When these fields change, the Structure script can build the import and export fields.

  1. Open Settings and go to the General tab.
  2. Select Use Smart Fields Creator.
  3. Enter a name, select the field type and the event, and click Add.

Field types:

Type Description
String Text value.
Password Entry from the Password Manager.
Directory Path Folder path.
File Name File path.
Button Button that calls the Structure script.
ComboBox Drop-down list. Add values with Add.
Separator Horizontal line between settings.
Environment Environment selection.
Event Function Calls the Structure script when an event happens. The Fields Changed event runs when fields are added.
Boolean Check box.

Events:

  • None: the Structure script is not called.
  • Changed and Changed\WPF: called when the value changes.
  • Click and Click\WPF: called when the button is clicked.
  • Connection and Connection\WPF: called when the plugin is connected to another plugin.

The WPF variants also show WPF windows if your script defines any.

The function that is called depends on the field:

  • A Button calls ButtonClick_<name>.
  • Fields Changed calls Event_FieldsAdded.
  • Other fields call DefaultValueChanged.

When you add a button or event, the editor adds the function to the Structure script. By default, it calls main(kwargs).

Structure script

The Structure script returns a JSON string that describes the plugin. It receives settings, structure, environment, id, description, version, and pm.

import json

def main(kwargs):
    fields = {
        'plain_field': {
            'name': 'plain_field',
            'type': 'string',
            'visible': True
        }
    }
    payload = {
        'description': 'Plugin description',
        'output_fields': {
            'fields': fields,
            'structures': {'structure': {'name': 'structure', 'fields': fields, 'type': 'structure'}},
            'tables': {'table': {'name': 'table', 'fields': fields, 'type': 'structurearray'}},
        },
        'input_fields': {}
    }
    return json.dumps(payload, ensure_ascii=False)

Python 3 uses different keys than Python 2. For example, use description, input_fields, output_fields, visible, default, attrs, and opts instead of descr, import, export, vis, dv, attr. Fields, structures, and tables are dictionaries keyed by name, not lists.

Top-level keys:

Key Description
description Plugin description.
upper_description Upper description shown on the right pane.
lower_description Lower description shown on the right pane.
settings Smart field settings to update.
config_close Closes the settings panel when True.
input_fields Import structure with fields, structures, and tables.
output_fields Export structure with fields, structures, and tables.

Field properties:

Property Description
name Field name. Required.
type string, int, float, structure, or structurearray. Required.
description Field description shown on the canvas.
default Default value.
tooltip Tooltip text.
visible Whether the field is visible.
attrs Attributes. Each has name, char, color, and optional selected and tooltip.
opts Options. Each has name and optional char, color, tooltip, editable, visible, and value.

Colors can be blue, green, red, yellow, or a HEX value (RGB, RRGGBB, ARGB, or AARRGGBB).

To show a pop-up message from the Structure script, use the VeloX message box:

import clr
clr.AddReference('VeloX.Core')
## MessageBox.ShowInformation('Informational notification')
## MessageBox.ShowWarning('Warning notification')
## MessageBox.ShowError('Error notification')

After Stop script

The After Stop script runs once after the migration when Call script after project stopped is on. Use it, for example, to close connections or clean up files. It receives settings, structure, environment, description, id, version, pm, and ev.

The After Stop script runs in a new interpreter, so it doesn't see the variables of the main script. Use ev to pass values from the main script to it.

Debugging

The debugger lets you run a script step by step.

  1. In Settings, open the Debug tab and select Use Debugger.
  2. Select the scripts to debug.
  3. Run the migration, or click Check & Debug in the editor.

Before a debug run from the editor, you can enter Input Data: and select Stop On First Line or Simulation.

In the Python Debugger window:

  • Continue (F5) runs to the next breakpoint.
  • Step Into (F10) runs the next line.
  • Get Global Variables shows the global variables.
  • Right-click a variable to copy its name, value, or row.

When Use Debugger is on for the Main Script, every item of the run opens its own debugger window and runs the script in a new interpreter. Module-level variables are not kept between items in this mode. Turn the debugger off for normal runs.

Create a plugin template

  1. Open Settings and go to the Template tab.
  2. Click Create Template.
  3. Enter PluginName, Description, Url, Version, and GroupName. You can also set the Icon Background.
  4. Choose the template options:
    • Close Template hides the source code in the plugin.
    • Close Field Creation disables manual field creation.
    • Remove All Fields removes the plugin structure.
  5. Add notes on the Notes tab.
  6. Add custom libraries on the Libraries tab with Add File or Add Directory.
  7. Click Save.

Logging

The plugin writes the following to the technical log: the plugin version, the input data, the returned metadata, the output data, and any Python errors with their line numbers. See Logging Manager.

The input data, metadata and output data sections are filled only with the Detailed logging mode. With the short log, these sections stay empty.

Esc