Resources

Getting Started with PyAnsys: A PyMechanical Workflow for Beginners

Written by Samuel Lopez | Jul 24, 2025 11:29:38 PM

If you're new to scripting or have limited experience with Python, the idea of automating Ansys Mechanical might feel a little overwhelming at first. Fortunately, the PyAnsys ecosystem (specifically PyMechanical, in this case) offers a practical entry point for engineers and analysts who want to streamline repetitive tasks, reduce setup time, and build reusable simulation workflows. This blog is designed to help new users understand what PyMechanical is, how it integrates with Ansys Mechanical, and how you can begin using it without needing to be an expert in Python. We'll cover high-level capabilities, walk through tool setup, and then explore a complete bolt pretension example using Jupyter Notebook, along with clear explanations of what each command does and how it connects back to the Mechanical interface you’re already familiar with.

 

What is PyMechanical?

PyMechanical is part of the broader PyAnsys ecosystem and serves as a Python interface for automating and controlling Ansys Mechanical. It acts as a bridge between Python and the Mechanical solver, allowing users to script and manipulate their simulation workflows programmatically instead of relying solely on the graphical user interface (GUI) within Workbench.

At its core, PyMechanical provides direct access to the same objects and commands you’d interact with in the Mechanical GUI (geometry, mesh controls, materials, boundary conditions, solver settings, post-processing, and more) but through Python code. This opens the door to a wide range of possibilities that go beyond what’s practical through point-and-click alone.

Here are some of the major advantages of using PyMechanical compared to traditional Workbench Mechanical:

    • Automation of Repetitive Tasks
      If you frequently work on similar models or need to run through the same setup steps across multiple simulations, PyMechanical allows you to encapsulate that logic into scripts. This eliminates manual rework and ensures consistency across models.

    • Batch Processing and Parametric Studies
      With Python’s looping and control structures, you can run hundreds of design variants, adjust parameters programmatically, or solve models in sequence—all without needing to babysit the GUI.

    • Version Control and Reusability
      Unlike GUI actions, scripts are text-based and can be stored in version control systems like Git. This makes it easier to review changes, track evolution, and reuse code across teams or projects.

    • Integration with Other Python Libraries
      PyMechanical can be combined with libraries like NumPy, pandas, or matplotlib for pre- and post-processing, data handling, or visualization. You can even integrate simulations directly into optimization loops, AI models, or data dashboards.

    • Headless Execution for HPC and Remote Use
      You can launch Mechanical in batch or non-GUI mode on a server or HPC cluster, which is ideal for scaling up simulations without needing a local workstation.

    • Advanced Post-Processing and Data Extraction
      PyMechanical allows scripted access to simulation results—such as stress, deformation, contact status, or reaction forces—and enables exporting, plotting, or comparing results across models automatically. This is especially useful when generating custom reports or integrating results into a larger engineering analysis pipeline.

    • Command-Level Control and Flexibility
      PyMechanical still supports inserting command snippets (such as APDL commands) when deeper control is required, such as defining contact key options or custom solver behaviors.

In short, PyMechanical gives you the same depth of control you’d expect from the GUI with the added power, precision, and repeatability that comes from using code. Whether you're trying to save time, scale up, or integrate simulations with larger systems, PyMechanical offers a path forward that is both flexible and highly efficient.

 

Two Ways to Use PyMechanical: Embedded vs Remote

There are two main ways to run a model using PyMechanical:

  1. Embedded Mode
    In this method, Mechanical is launched as an object directly inside the Python environment. You can script your entire workflow without even opening the GUI. This is ideal for fully automated workflows or when running Mechanical in the background.

  2. Remote Session Mode
    In this method, Python connects as a client to a standalone instance of Mechanical running in the background. This can be on the same machine or a remote server. It's useful when you want to keep the GUI open and interact visually, while still automating parts of the process.

Both methods allow full access to Mechanical’s scripting API, but your choice will depend on how much GUI interactivity you want. This example will utilize the Remote Session option.

 

Getting Started with Python and PyMechanical

If you’re new to Python, don’t worry. It’s widely used in engineering and relatively easy to learn. There are a few tools commonly used to run Python:

  • Jupyter Notebook: Interactive and step-by-step. Great for testing and documentation.

  • Spyder: IDE with a MATLAB-like layout. Part of the Anaconda package.

  • VS Code: Lightweight, customizable editor with Python plugins.

You can use any of these tools based on personal preference. For this blog, we’ll be working in Jupyter Notebook.

We also recommend exploring the Ansys Innovation Space, which offers a short, beginner-level course on Python basics if you’re just getting started.

To install PyMechanical:

pip install ansys-mechanical-core

 

Or install Anaconda, which bundles Python, Jupyter, and Spyder, and then run the same pip install command within that environment.

 

Understanding the Syntax of PyMechanical

Before we dive into the example, let’s take a moment to understand how the Python commands are structured when interacting with Ansys Mechanical.

PyMechanical uses the same object model as the Mechanical GUI. This means when you access or modify parts of the simulation using Python, you're referring to the same internal objects and trees you’d see in the GUI.

Here’s the general structure:

  • Top-level object: Model is the root of your simulation setup (geometry, mesh, materials, analyses, etc.)

  • Branches: You access specific areas using branches like Model.Geometry, Model.Mesh, Model.Analysis, or Model.Connections

  • Methods: Actions like AddStaticStructuralAnalysis(), Import(), or AddForce() are methods applied to those objects

  • Properties: Attributes like Material, SolverType, or Location define the values or scoping of a given item

For example:

Model.AddStaticStructuralAnalysis()

 

This line creates a new static structural system, just like dragging one in from the Workbench toolbox.

SURFACE1.Material = "Steel"

 

This assigns a material to a specific solid body, just like selecting a part and choosing from the drop-down in the GUI.

In PyMechanical, most interaction is done by running Mechanical scripting commands from Python using run_python_script(). These commands follow the same internal scripting structure Mechanical uses under the hood.

 

Walkthrough Example: Bolt Pretension Analysis

Now let’s walk through the bolt pretension example provided by the PyMechanical examples page. We’ll explain each section as we go, with emphasis on the syntax and reasoning behind each line. 

 

Step 1: Launch Mechanical

Start Mechanical in the background:

from ansys.mechanical.core import launch_mechanical
mechanical = launch_mechanical()

 

This creates a mechanical Python object representing the Mechanical instance.

You can also open the GUI for interactive work:

mechanical = launch_mechanical(batch=False)

 

Step 2: Download Geometry and Materials

from ansys.mechanical.core.examples import download_file

geometry_path = download_file("example_06_bolt_pret_geom.agdb", "pymechanical", "00_basic")
mat_cop_path = download_file("example_06_Mat_Copper.xml", "pymechanical", "00_basic")
mat_st_path = download_file("example_06_Mat_Steel.xml", "pymechanical", "00_basic")

 

This downloads the CAD and material files needed for the simulation from the example repository.

Step 3: Upload Files to Mechanical

 

project_directory = mechanical.project_directory
mechanical.upload(file_name=geometry_path, file_location_destination=project_directory)

 

Here, we’re sending the geometry file to the active Mechanical session’s working directory.

Step 4: Import Geometry

 

mechanical.run_python_script("""
geometry_import = Model.GeometryImportGroup.AddGeometryImport()
geometry_import.Import(part_file_path)
""")

 

This imports the geometry into the project. It’s the scripted equivalent of right-clicking the Geometry cell and choosing "Import Geometry."

Step 5: Create Named Selections

 

mechanical.run_python_script("""
NS_GRP = ExtAPI.DataModel.Project.Model.NamedSelections
shank_face = [x for x in ExtAPI.DataModel.Tree.AllObjects if x.Name == 'shank_face'][0]
""")

 

This finds and stores specific named selections (already created in the geometry file) for later use when defining contacts and loads.

Step 6: Add Static Structural Analysis

 

mechanical.run_python_script("""
Model.AddStaticStructuralAnalysis()
STAT_STRUC = Model.Analyses[0]
""")

 

This creates a new static structural analysis system and saves a reference to it for subsequent commands.

Step 7: Import Materials and Assign to Bodies

 

mechanical.run_python_script("""
Model.Materials.Import(mat_Copper_file_path)
Model.Materials.Import(mat_Steel_file_path)
""")

 

Since Workbench's libraries aren't available in PyMechanical's standalone mode, we manually import material XML files.

Material assignment works by navigating the geometry tree and assigning the material:

GEOM.Children[0].Children[0].Material = "Steel"

 

This means “the first part under the geometry tree gets Steel assigned.”

Step 8: Define Contacts and Insert Archard Wear Model

 

CONT_REG1 = Model.Connections.AddContactRegion()
CONT_REG1.SourceLocation = NS_GRP.Children[0]
CONT_REG1.TargetLocation = NS_GRP.Children[1]
CONT_REG1.ContactType = ContactType.Frictional

 

This defines a contact between two named selections. Additional parameters like friction coefficient and stiffness updating are also set here.

To add wear modeling, an APDL command snippet is inserted:

 

CMD1.AppendText("keyopt,cid,9,5\nrmodif,cid,23,0.001")

 

This shows how APDL commands can be used within PyMechanical to set up features like the Archard Wear Model.

Step 9: Define Analysis Settings

 

STAT_STRUC_ANA_SETTING.NumberOfSteps = 4
STAT_STRUC_ANA_SETTING.SetNumberOfSubSteps(1, 2)
STAT_STRUC_ANA_SETTING.SolverType = SolverType.Direct

 

These lines define how the analysis will be solved: how many steps, substeps per step, solver type, etc.

Step 10: Add Loads and Bolt Pretension

 

Bolt_Pretension = STAT_STRUC.AddBoltPretension()
Bolt_Pretension.Location = shank_surface
Bolt_Pretension.Preload.Output.DiscreteValues = [...]

 

This is a full-featured bolt pretension setup—done entirely from Python. The preload is defined over time, and SetDefineBy is used to lock the bolt after the load is applied.

Step 11: Add Post-Processing Items

 

STAT_STRUC_SOLN.AddTotalDeformation()
STAT_STRUC_SOLN.AddEquivalentStress()

 

Post-processing objects are added directly to the solution branch. These results will be available once the model is solved.

Final Thoughts

PyMechanical bridges the gap between powerful GUI workflows and flexible scripting control. Whether you choose the embedded or remote session method, you can automate everything from geometry import to results extraction, and even insert APDL snippets when needed.

If you're just starting out with Python, don’t be intimidated by the syntax. Each line simply reflects something you’d do in the GUI, just written as a command. The more you use it, the more natural it becomes.

In future posts, we’ll explore how to loop through parametric designs, batch solve multiple load cases, and visualize results programmatically. Until then, this bolt pretension example is a great place to start.