Error message

Notice: Undefined index: gdpr_consent in mailchimp_signup_subscribe_form() (line 380 of /usr/www/users/qfinsgbjyt/sites/all/modules/mailchimp/modules/mailchimp_signup/mailchimp_signup.module).

Ansys Mechanical Scripting

Written By: 
Jesse Quick

Automating repetitive tasks is one thing I love to do. Not only does scripting save you time, it helps eliminate unnecessary errors. In this blog we will look at using scripting in Ansys Mechanical and the process will then be demonstrated in the video series in more detail. 

Getting started

In Ansys Mechanical, the scripting functionality can be accessed under the Automation tab. Scripting in mechanical uses Python as the programming language. To take full advantage of all of all the features, a knowledge of Python and its syntax is recommended.

In the scripting panel, you have access to the shell and script editor. The editor is where you can work with long scripts for your workflows. The shell is used for shorter commands to build your scripts. To demonstrate the basics of the scripting I can access a model’s mesh data by typing the following in the shell.

>>> mesh=DataModel.AnalysisByName("Static Structural")

>>> mesh_size=mesh.MeshData.ElementCount

>>> mesh_size

The autocomplete tool is useful to see your options for what you can do next. This comes up every time you insert a period “.”.

There is a method to use journaling, this will effectively record a macro for the operations you perform in Mechanical. The journaling feature is still a beta feature but can be enabled in the Workbench environment

Video 1 of the series is an introduction into the scripting environment and shows the basics of using the API.



Basic functionality

With scripting there are multiple ways to perform the same operations and access information.

The key tool you have access to is the autocomplete tool. This can help you see available commands and gives an indication if your code is working. Next to the available options further details are given such as the required input information and what it will return.

If you do need more information on something you can always type help and the argument you need help with and it will give a printout of the help for that. For example:

>>> help(DataModel)

With all of the options available it can help to understand how to navigate through the structure tree and using the API.  The tree can be accessed directly from the API if you select a branch in the tree and run the following line in the shell.

>>> Tree.ActiveObjects

This will then return the branch of the tree you have currently selected.


The DataModel effectively stores the data for the entire model. The data can be accessed using indexing or names. To access the data of the Static Structural analysis we can use either of the following lines of code.

>>> DataModel.AnalysisList[0]

>>> DataModel.AnalysisByName("Static Structural")


Within branches you can access the sub-branches/children. The connections information can be accessed by either:

>>> Connections=DataModel.Project.Model.Connections

>>> Connections = Model.Children[4]

In this case I would like to just see the first contact region type, by typing:

>>> Contact_group= Connections.Children[0]

>>> Contact1=Contact_group.Children[0]

>>> Contact1.ContactType

From here you can change the contact type:

>>> Contact1.ContactType=ContactType.Frictionless

For more information on the basics and navigating in the API see video 2 of the series.


All objects and methods have a unique ID. The ID is not always clear but that can be found out rather easily.  You can select objects in the GUI and run the following to get all of the objects IDs.

>>> ExtAPI.SelectionManager.CurrentSelection.Ids

Sometimes the model becomes complex and in order to access the information you need to access the data for the object. A quick and simple method is to select the branch you want information of and run the following:

>>> Tree.GetPathToFirstActiveObject()

In the correct branch you can find all of the properties relevant to the branch.

>>> Contact1.VisibleProperties

This returns a list of all the visible properties that we have access to in a list form.


One of the tasks that can benefit the most from automation would be applying boundary conditions. The way I prefer to do it is to make a named selection and apply boundary conditions to named selection. For example, I will demonstrate how apply a pressure. first create a named selection “P” on selected faces and then create a pressure with the following code:

>>> Named_selections = DataModel.GetObjectsByName("P")

>>> Pressure=DataModel.AnalysisList[0]

>>> My_pressure=Pressure.AddPressure()

>>> My_pressure.Location= Named_selections[0]

>>> My_pressure.Magnitude.Output.DiscreteValues=[Quantity('1 [MPa]')]

The Quantity command, as seen above, is used to define values. To demonstrate how to use this I can change the contacts pinball radius.

>>> Contact1.PinballRadius

>>> Contact1.PinballRadius= Quantity("5 [mm]")


For boundary conditions we have inputs and outputs. The input is typically time and the output is the magnitude of the load or displacement. To demonstrate the inputs and outputs I will now redefine my pressure to be a discrete function of time using the following code:

>>> Named_selections = DataModel.GetObjectsByName("P")

>>> Pressure = DataModel.AnalysisList[0]

>>> My_pressure = Pressure.AddPressure()

>>> My_pressure.Location = Named_selections[0]

>>> My_pressure.Magnitude.Inputs[0].DiscreteValues = [Quantity('0 [sec]'), Quantity('1 [sec]'), Quantity('2 [sec]')]

>>> My_pressure.Magnitude.Output.DiscreteValues = [Quantity('0 [Pa]'), Quantity('50 [Pa]'), Quantity('100 [Pa]')]

There are far more details to discuss for boundary conditions. To see a demonstration and explanation for the useful code and boundary conditions, have a look at video 3 of the video series.


Additional concepts and tips and tricks

As there is so much to cover for the scripting functionality, I have selected fundamental applications and tried to cover all the bits and pieces in between, two features I would like to highlight are looping and using external modules.

The first is looping. In python you can use looping to do repetitive tasks. A simple example is to use a for loop.

>>> for i in range(5):

>>>     print(i)

Effectively, in a loop, whatever is indented will be repeated a set number of times.


External modules/libraries can be imported into the API for specific tasks. In order to use these libraries, you will need to import them. To use mathematical functions and constants there is the math module. For working with csv files, such as tables, you can import the csv module. You can also read and write txt and csv files. The following lines of code can be used import the modules and to read and write data.

>>> import math as m

>>> import csv

>>> open()

>>> write()

>>> close()


Approach and suggestions

To finish off the demonstration, I will give a very brief overview of my approach to using the scripting API and then onto the tips and tricks.

Approach to getting started:

  • As expected, the first thing to try is google, you will not always find the exact solution but you might find something similar. There might not be Ansys Mechanical specific help, but there is a large collection of resources for python help.

  • When I start writing the code, I will always try to get my script to work with one instance first. For example, if I need to scope a boundary condition to many different geometries, I will only look at one to start, then try 5 and progressively move up from there.

  • Look at what the input and output data is and the type of data required. This will help you to see what you are working towards.

  • You can use the journal recording and try work backwards from there.

  • Finally, if all else fails, write out you coding process by hand. This forces you to evaluate your logical process and helps you understand the coding process.


Tips and tricks:

  • The first tip is to save your code regularly.

  • Use variables often and liberally, but don’t be lazy with your naming. Keep it as accurate as possible, this is a long-term strategy for remembering how code works at a later point.

  • I like to use named selections for scoping. Named selections can be used throughout the process from geometry, to material assignment, meshing, applying supports, boundary conditions and results.

  • Comments, comments and more comments. Commented code gives an explanation for the code and makes it readable in the future. Comments help in the future for when you want to reuse some code that did something similar in the past or when you pass your code on to colleague to use.

  • Practice and explore.


There are more features and modules that can be used. To see a demonstration of using these modules and further explanations for the tips and tricks see video 4 of the series.



With this I hope you have found the information given useful and ultimately that this will save you time. Please give us feedback on this content, this will help us improve future content.




  • I would like to hereby express my vote of confidence in Qfinsoft, in their ability to service and provide a strong support to us as a company.  We have been a customer of Qfinsoft for over a year and I am pleased to compliment them on their impeccable service offered to us thus far

    - Nico Gunther, Powertech Transformers

  • Since the introduction of ANSYS, more students are using first principles and FEA to validate their designs. This year, more than 60% of the projects were using FEA as a standard approach for numerical calculation. This number shows the huge impact ANSYS, had on University of Pretoria. FEA is not anymore a specialised tool for few users but a standard engineering tool easily integrated in the design process.

    - Francesco Pietra, University of Pretoria

  • For their consulting, training and technical support, Qfinsoft (Pty) Ltd must be the first choice of any firm looking for CAE experts

    - Prof G Akdogan, Process Engineering, University of Stellenbosch

  • At Aerospace, we have successfully used the ANSYS suite of tools to design high-performance gas turbine engines. Throughout this program, Qfinsoft provided valuable support and assistance to accelerate the development of our models. Their accessibility, short-turn around times and willingness to go beyond what is expected make them an effective partner on our projects. 

    - Dr. Hannes Pretorius

Our Clients