BlogCAD Automation

SolidWorks Automation with the Python API

An introduction to scripting against the SolidWorks API to cut repetitive design work — COM connection, parameter updates, session handling, and where Python ends and C# begins.

  • 5 min read
SolidWorks Automation with the Python API
In This Article

Automating repetitive CAD operations in the SolidWorks ecosystem is one of the most direct ways to cut the repetitive modelling load off an engineering team. Python can drive that automation through the COM interface or .NET bridges and is excellent for rapid prototyping; in production, C# / .NET is usually the better choice.

SolidWorks API otomasyonunu temsil eden illüstrasyon
The SolidWorks automation and API layer
01 / 06

The API connection model

SolidWorks automation typically consists of opening an application session, taking a reference to the active document or assembly, updating through the feature and dimension APIs, and generating output. The scripting language should be chosen on performance, deployment, and the team's existing skills.

Python suits fast experiments and automation scripts; C# / .NET is more common in enterprise add-in and macro architecture.
02 / 06

COM connection: the first working script

On the Python side, the route into SolidWorks is the COM interface. Opening a session with pywin32 takes a few lines, but two things must be right from the start: checking whether the application is already open, and setting visibility explicitly.

import win32com.client as win32

# Dispatch attaches to a running session, or starts a new one.
sw = win32.Dispatch("SldWorks.Application")
sw.Visible = True

model = sw.ActiveDoc
if model is None:
    raise RuntimeError("No open document — open a part or assembly first.")

print(model.GetTitle(), "|", model.GetType())

The return value of GetType() decides everything that follows: 1 is a part, 2 an assembly, 3 a drawing. The first branch of the automation separates right here — applying part logic to an assembly is the most common mistake.

03 / 06

The right way to update parameters

Pulling dimensions one by one off the Dimension object works, but it is brittle: rename a feature and the script goes silent. The more durable route is to drive the design through global variables; dimensions bound to the equation table are then managed from a single point.

def set_global(model, name: str, value_mm: float) -> None:
    """Update a global variable. SolidWorks expects metres, so convert from mm."""
    eq = model.GetEquationMgr()
    for i in range(eq.GetCount()):
        if eq.Equation(i).startswith(f'"{name}"'):
            eq.Equation(i, f'"{name}" = {value_mm}mm')
            return
    raise KeyError(f"Global variable not found: {name}")

set_global(model, "Width", 2400)
set_global(model, "Height", 1800)

# Force the rebuild: True rebuilds the whole tree.
model.ForceRebuild3(True)

ForceRebuild3(True) is expensive. In batch work it should be called once after the whole parameter set is written, not after every parameter.

Parametrik tasarım sürecini temsil eden illüstrasyon
Parametric input and the rule panel
04 / 06

Session handling and error trapping

The number one reason automation scripts blow up in production is the modal dialog SolidWorks opens: a warning appears, the script waits for an answer, and the operation hangs forever. The fix is to disable user prompts at the start of the run.

errors = win32.VARIANT(win32.pythoncom.VT_BYREF | win32.pythoncom.VT_I4, 0)
warnings = win32.VARIANT(win32.pythoncom.VT_BYREF | win32.pythoncom.VT_I4, 0)

model.Save3(1, errors, warnings)   # 1 = save silently
if errors.value != 0:
    raise IOError(f"Save failed with code: {errors.value}")

The VARIANT wrappers here exist for COM's ByRef parameters; this is the detail that costs the most time in Python. Do not move to the next step without checking the error code — a silent save also means a silent failure.

05 / 06

Producing the output package

Emitting PDF, DWG, and DXF in one command is the benefit of automation people feel most on the shop floor.

from pathlib import Path

def export(model, out_dir: Path, stem: str) -> None:
    out_dir.mkdir(parents=True, exist_ok=True)
    for ext in ("pdf", "dwg", "dxf"):
        target = out_dir / f"{stem}.{ext}"
        ok = model.SaveAs3(str(target), 0, 2)   # 2 = silent
        if not ok:
            print(f"WARNING: could not produce {ext.upper()} → {target}")

Naming, folder structure, and revision numbering must be part of the automation. Otherwise the files get produced but nobody knows which revision sits in which folder; the time you saved goes back out as time spent searching.

06 / 06

Where Python ends and C# begins

Python is the exploration language for this work: you can try an idea in half an hour and see whether it holds. But for an add-in that goes to production I choose C# / .NET, for three reasons:

  1. Deployment. Installing a Python interpreter and its dependencies on a user's machine is far more fragile than installing one signed add-in DLL.
  2. Performance. When the number of COM calls climbs (assemblies with hundreds of components), managed code's direct API binding is markedly faster.
  3. Interface. A panel embedded in the SolidWorks Task Pane is incomparably more natural for the user than an external script window.
A practical rule: validate the idea in Python, write the flow that will last in C#. The bridge between them is that both sides read the same rule set — so put the rules in data, not in code.
İlgili projeAI Destekli SolidWorks Add-inAI destekli SolidWorks Add-in: parametrik tasarım, 2D→3D otomasyon ve CAD workflow'unu yazılımla tanımlayan mühendislik yazılımı projesi.