21.2. Using Python Code for Event Based Code Execution

In addition to executing Python code during the solution process, each Python object you insert into the Outline has a Target Callback property that specifies when the object’s code should execute based on Mechanical events. The following example of the Details pane shows the Target Callback property options for a Python Code object inserted under the Solution object.

Specifying Callbacks

The options contained in the Target Callback property is based on where in the tree you add the Python Code object. The application executes callbacks when their parent object is processed. If more than one Python Code object is contained under the same parent, the application executes each object.

The exception is the Model object. If a Python Code object is contained under the Environment object with the Target Callback property set to After Object Changed, the code is only executed if any object under the Environment changes. However, for a Python Code object that is contained under the Model object with the Target Callback property set to After Object Changed, the code is executed when any object in the system changes.

Parent ObjectTarget Callback Options

Model

After Mesh Generated

After Geometry Changed

After Object Changed

Body

Get Body Commands

After Object Changed

Contact Region

Get Contact Commands

After Object Changed

Environment

Get Solve Commands

Before Solve

After Object Changed

Solution

Get Post Commands

After Solve

After Post

After Object Changed

Connecting Callbacks

When the text of the Python Code object is modified, the object becomes under-defined as the Python code is no longer connected to the callback. It is necessary to connect the code changes once completed or the code will not be executed. Note that as soon as you start editing the text in the editor, the Python Code object will become under-defined and the Details pane will indicate that the Connected property of the Python Code object has become false. At this point, once you are finished making your code changes, use the Connect button in the context tab in the ribbon or use the right-click context menu on the object in the tree to Connect the Python Code object.

Example

Here are some examples of the default content for a Python Code object inserted under the Solution object with the Target Callback property set to After Post and After Solve. The function name corresponds to the type of event.

At the top of the editor, you will see a function which will take in different arguments based on different callbacks. In the following examples, the "after" callbacks takes in "this" and "solution" as arguments to this function definition. Any code that you want to execute on the given event should be placed within the function definition replacing the pass.