Skip to main content

Script Tip Friday- Communicate with the Project Page from within Mechanical

| 06.03.2022

Thanks for joining us for another Script Tip Friday! This week, we introduce the brilliant Landon Kanner, a Lead Consulting Engineer at Ansys. Landon helps answer a question we get all the time- how to communicate with the Project Page from within Mechanical.

"How do I communicate with the Project Page from within Mechanical? The answer is to utilize the wbjn module, whose source code can be found in the ACT installation directory (more on that later). In theory, you can run project page commands from Mechanical like this:

import wbjn

WB_cmds = '''My Workbench commands here'''
wbjn.ExecuteCommand(ExtAPI,WB_cmds)

However, the above snippet is pretty useless so far, because:

  1. It does not allow us to return any information to Mechanical
  2. If the Workbench commands modified project in any way, Mechanical and/or Workbench would crash. This is due to a threading issue.

To retrieve information from the Project Page and return it to Mechanical, we use the returnValue function. Here is a common example:

import wbjn

WB_cmds = '''
my_directory = GetUserFilesDirectory()
returnValue(my_directory)
'''

UserDirectory = wbjn.ExecuteCommand(ExtAPI,WB_cmds)

If we want to make modifications to the Project Page, we need to interact with the Project Page on a separate thread from Mechanical. Here is an example to change the name of a system in the Project Page from within Mechanical:

import System
from System.Threading import *

def RunWBJN(cmds):
  def Internal_RunWBJN():
    import wbjn
    wbjn.ExecuteCommand(ExtAPI,cmds)
  thread = System.Threading.Thread(System.Threading.ThreadStart(Internal_RunWBJN))
  thread.Start()

project_cmds = '''
system1 = GetAllSystems()[0]
system1.DisplayText = "my name"
'''

RunWBJN(project_cmds)

The above examples make use of one of several useful libraries, which can be found in the Ansys installation directory under: \Addins\ACT\libraries\Mechanical. For example: C:\Program Files\ANSYS Inc\v221\Addins\ACT\libraries\Mechanical Here is an example from another such library:

import units

units.ConvertUnit(1,'MPa','psi')

I suggest you take a look at all the libraries in this folder. There are lots of useful functions and studying the source code can be an invaluable learning resource. Already using these libraries? Please post your examples in the comments below.