Method to send path addresses between Workbench and Mechanical

M Member, Employee Posts: 199
First Comment First Anniversary Ansys Employee Solution Developer Community of Practice Member
edited June 2023 in Structures

In Workbench you can send commands to Mechanical.

myCmd = """ # must be in triple quotes"""
modelContainer.SendCommand(Language="Python", Command=myCmd)

But it is difficult to get address paths to be sent due to some change in the slash direction (/ change to \ or you need doubles, etc. Trust me, it is a pain and a problem). The triple quotes (and internal single) does not make it easier.

A work around that requires a few extra lines is to break the address path into a list of strings in Workbench.

import os
projectDir = GetProjectDirectory()
dirList = projectDir.split(os.sep)

Here the dirList is a list with the individual directories in the original project directory. os.sep or the operating systems separator is used to split the path address.

Then in mechanical you can send the list and re- assemble it into the original path.

The example below is cut from an example where a function in Workbench is used to create the required command to be sent to Mechanical.

fileName = 'something.csv'
def myFunc(sysName,dirList):
    myCmd = """
import os, json , codecs
fileName = '%s'
dirList = %s
path = dirList[0] + os.sep
for p in dirList[1:]:
  path = os.path.join(path,p)
path = os.path.join(path, fileName)
  return myCmd

Then in Workbench you can use this function using the dirList and a file name as input arguments. The two arguments are set to parameters in the %s lines and the path is rebuilt in Mechanical.

newCmd= myFunc(fileName,dirList)
modelContainer.SendCommand(Language="Python", Command=newCmd)

Naturally this might be improved, but it works around the problem of the address paths getting changed and failing when being sent to Mech.