BlogCAD Automation

SolidWorks Python Scripting: pywin32 Code and COM Traps

SolidWorks Python scripting with pywin32: connect to the API over COM, drive dimensions, rebuild once, export PDF or DXF — and dodge the COM traps.

  • 13 min read
In This Article

SolidWorks Python scripting is a practical way to automate parts, assemblies, and drawings through the same COM-based SolidWorks API that VBA and C# use. With pywin32, you connect to SldWorks.Application, open or attach to a document (IModelDoc2), change parameters, rebuild, save, and export PDF or DXF — without writing a full add-in first.

This guide covers how Python automation connects to SolidWorks, the COM traps that waste the most time in production, minimal code patterns you can run today, and when a script should become a C# add-in. If you are scoping a first project, how to start a CAD automation project pairs well with the workflow here.

Kod parçasını temsil eden illüstrasyon
Python: the exploration language of SolidWorks automation
01 / 09

How Python connects to SolidWorks

SolidWorks exposes its automation surface through COM. On the Python side, pywin32 (win32com.client) creates the bridge to SldWorks.Application — the root of the API object tree documented in the official SolidWorks API Help.

Three connection patterns matter in daily scripting:

  • `Dispatch` — starts SolidWorks if it is not running, or attaches to a new invisible session.
  • `GetActiveObject` — attaches to an already open SolidWorks instance (useful when engineers work interactively).
  • `ActiveDoc` — returns the active IModelDoc2; empty if no file is open.

After you have the application object, document type drives everything: PartDoc, AssemblyDoc, and DrawingDoc behave differently. Applying part logic to an assembly is still the most common early mistake.

Where you are probably stuck in setup

On the Python side, the biggest time sink is not the code — it is architecture mismatch. A 32-bit Python cannot talk to 64-bit SolidWorks; the COM error rarely says that plainly. Match bitness: 64-bit SolidWorks requires 64-bit Python.

The second common issue is the COM type library not being generated on first run. pywin32 constants such as swDocPART are cached on first access; until then, use numeric document-type values or generate the type library once.

02 / 09

Practical Python examples

The snippets below are minimal patterns for SolidWorks Python scripting — connect, read the active document, change a driving dimension through a global variable, rebuild once, save, and export. Adjust names to match your model's equation table and file paths.

Connect to SolidWorks

Python
import win32com.client

# Start or attach to SolidWorks
sw = win32com.client.Dispatch("SldWorks.Application")
sw.Visible = True

To attach to an already running session:

Python
import win32com.client

sw = win32com.client.GetActiveObject("SldWorks.Application")

Get the active document

Python
model = sw.ActiveDoc
if model is None:
    raise RuntimeError("No document open")

doc_type = model.GetType()  # 1=part, 2=assembly, 3=drawing

Change a dimension through a global variable

Driving through global variables (equation-table names) is more stable than hard-coding feature dimension IDs. The API stores lengths in metres — 2400 mm is 2.4:

Python
eqn_mgr = model.GetEquationMgr()
# Index -1 appends; equation text uses metres in API units
eqn_mgr.Add2(-1, '"Width"=2.4', True)

For a named model dimension tied to a sketch:

Python
param = model.Parameter("D1@Sketch1")  # name depends on your model
param.SystemValue = 2.4  # metres

Rebuild once after all parameter writes

Python
model.ForceRebuild3(False)

Write every parameter first, then rebuild once. Rebuilding after each change is the usual reason batch scripts slow down by an order of magnitude.

Save the document

Many API methods return status through ByRef out-parameters in COM. In Python, wrap them with win32com.client.VARIANT:

Python
import pythoncom
import win32com.client

errors = win32com.client.VARIANT(pythoncom.VT_BYREF | pythoncom.VT_I32, 0)
warnings = win32com.client.VARIANT(pythoncom.VT_BYREF | pythoncom.VT_I32, 0)
ok = model.Save3(1, errors, warnings)
if not ok:
    raise RuntimeError(f"Save failed — errors={errors.value}, warnings={warnings.value}")

Always inspect result codes; unchecked saves are how silent data loss enters production automation.

Export PDF or DXF

Export paths and options vary by document type; a typical drawing export uses Extension.SaveAs:

Python
pdf_path = r"C:\Output\part-rev-A.pdf"
result = model.Extension.SaveAs(
    pdf_path,
    0,  # save version — use constants from the type library when available
    0,
    None,
    errors,
    warnings,
)

Check each format separately — a successful PDF does not guarantee DXF or DWG export succeeded.

For drawing-heavy output packages (naming rules, folder structure, multi-format batches), the same patterns appear in 2D drawing to 3D model automation workflows where geometry and release packages must stay aligned.

03 / 09

The right way to drive parameters

Most automation boils down to one job: change the dimensions, rebuild the model, take the output. The trick is in the first step.

Pulling dimensions one by one through features works, but it is fragile: the moment a feature is renamed the script goes quiet without any error. A far more durable route is to drive the design through global variables.

A global variable is a named number you define in SolidWorks' equation table — "Width", "Height" and so on. The model's dimensions bind to those variables. Your script now touches a name, not geometry. Feature names can change on the model side and the automation keeps working.

Then there is the units question, and this is the trap Python users fall into most often: the SolidWorks API works in metres. Even if your document displays millimetres, the number you write in code is read as metres. To set 2400 mm you write 2.4. Forget it and the model grows a thousandfold — and in batch runs that is not always visible to the eye.

Call rebuild in the right place

After changing parameters the model has to be rebuilt. But rebuilding is expensive.

The common mistake is rebuilding after every parameter. Twenty parameters means twenty full rebuilds — and the runtime goes from seconds to minutes. The correct approach is to write all parameters and then rebuild once.

In batch operations, that single decision is the difference between a runtime that multiplies and one that stays reasonable.

Yerel süreç ve bağlantı katmanını temsil eden illüstrasyon
The COM bridge: same API, different door
04 / 09

Session management: keeping the script from hanging

The number one reason Python scripts die in production is SolidWorks' modal dialogs. A warning window opens, the script waits for an answer, and the operation hangs forever. The script you started to run overnight is waiting for you at file three in the morning.

The fix is to disable user interaction at the start of the run: silent mode for opening and saving, plus general warning suppression. Remember to switch it back at the end — otherwise you will see no warnings at all until SolidWorks is restarted.

But turn that silence into a record: every warning you suppressed was telling you something. Have the script print a list at the end — "these files produced these warnings."

COM's `ByRef` trap

This is the technical detail that costs the most time on the Python side. Many SolidWorks API methods return their result not as a return value but by writing into variables you hand them. In C# and VBA that is natural; in Python it needs a special wrapper.

The practical consequence: to read the error code of a save or an export, you have to set those wrappers up correctly. Skip it and the operation still runs — but you never see the error code, which is an open door to silent failure.

The rule is always the same: do not move to the next step without checking the result code. A silent save, unchecked, means silent data loss.

05 / 09

Producing output packages: the most visible benefit

Producing PDF, DWG, DXF and bend drawings with one command is the part users respond to most. The reason is simple: the result is immediately visible and nobody asks whether it really saved anything.

Three things to watch:

The naming rule must be part of the automation. Project code, part number, revision — bind them all to a rule. Otherwise files get produced but nobody knows which revision sits in which folder, and the time you saved goes back into searching.

Let the script create the folder structure. If the target folder does not exist, create it. "Folder not found" is the stupidest possible reason for an overnight run to stop.

Check each format's result separately. A PDF being produced does not mean the DXF was. All three return their own result code.

Üretim hattını temsil eden illüstrasyon
The output package: automation whose result is visible immediately
06 / 09

Where Python ends and C# begins

This is the most frequent question, and my answer is clear: Python is the exploration language here, C# the production one.

Where Python genuinely shines is testing an idea in half an hour and seeing whether it works. No restart, no compile, no project setup. If you have a hypothesis — "can I drive this product family from parameters?" — Python answers it fastest.

But for an add-in that goes to production I prefer C# / .NET for three reasons:

Deployment. Installing a Python interpreter and its dependencies on a user's machine is far more fragile than installing a single signed add-in. And the cost of that fragility is paid not by you but by the user asking for support.

Performance. When the COM call count rises — in an assembly with hundreds of components — managed code's direct API binding is markedly faster. Every COM call has a cost, and on the Python side that cost is higher.

Interface. A panel embedded in the SolidWorks Task Pane feels incomparably more natural to a user than an external script window. If the automation feels like part of SolidWorks, people adopt it; if it requires opening a separate window, most of the time they simply do not use it.

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.

How to make that transition and how to structure the add-in is covered in writing a SolidWorks add-in with AI-assisted development and in production measurement practices in measuring automation ROI.

07 / 09

Where to start: your first script

A concrete suggestion: let your first script change nothing and only read.

A script that prints the open document's name, type and the feature names in the design tree takes ten minutes to write and teaches you two things at once: that the connection works, and how you navigate the object hierarchy. And it carries no risk.

Your second script should read a global variable. The third should change one — but on a copy of the file. Testing on a live project is the most expensive way to learn.

Follow that order and within a week you will have a working automation. More importantly, you will know why it works.

08 / 09

Frequently Asked Questions

Can SolidWorks be automated with Python? Yes. SolidWorks exposes its automation interface over COM, and Python's pywin32 library bridges to SldWorks.Application. You call the same API surface as VBA or C# — only the language binding differs.

Does SolidWorks have a Python API? There is no separate "Python API." Python uses the standard SolidWorks COM API through pywin32. Official documentation is written for the object model (SldWorks, IModelDoc2, IPartDoc, etc.), not for a Python-specific SDK.

How do I connect Python to SolidWorks? Install 64-bit Python and pywin32, then use win32com.client.Dispatch("SldWorks.Application") or GetActiveObject to attach to a running session. Match Python bitness to SolidWorks.

Is pywin32 required? For COM automation on Windows, yes — pywin32 is the standard bridge. Alternatives still talk to the same COM ProgID; they do not remove the COM model underneath.

Can Python edit SolidWorks dimensions? Yes — through dimension objects, equations, or global variables. Global variables are usually the most stable contract between script and model.

Can Python export SolidWorks drawings to PDF or DXF? Yes, through Extension.SaveAs and format-specific options. Verify each export's return code; PDF success does not imply DXF success.

Can Python automate assemblies? Yes, via AssemblyDoc and the same IModelDoc2 entry point, but assembly logic differs from parts. Identify document type before applying operations.

Can Python replace a SolidWorks macro? For exploration and one-off batch tasks, often yes. For team-wide, rule-heavy flows with UI inside SolidWorks, macros or add-ins are usually the durable home.

Why do I get errors connecting to SolidWorks from Python? The most common cause is an architecture mismatch: you cannot connect to 64-bit SolidWorks from 32-bit Python, and the error does not say so. The second common cause is the COM type library not being generated, which makes the named constants unrecognised.

What units does the SolidWorks API use for dimensions? System units — metres. Even if the document displays millimetres, a number written in code is read as metres; for 2400 mm you write 2.4. This is the most insidious bug in automation because the result is not always visible to the eye.

Should I update parameters through features or global variables? Global variables. Feature-name-based updates go silently dead the moment something is renamed on the model side. A global variable sets a stable contract between script and model.

My script hangs on a dialog — what should I do? The cause is a modal warning window opened by SolidWorks. Enable silent mode for opening and saving at the start of the run and restore it at the end; also have the script print the suppressed warnings as a report.

Python or C#? Python for exploration and validating ideas — nothing else is this fast. C# / .NET for flows that go to production, that a team will use, and that must live inside SolidWorks; deployment, performance and interface all point to C#.

My batch run is slow — how do I speed it up? The most common cause is rebuilding the model after every parameter change; rebuild once, after all parameters are written. The second is leaving screen updates on — turning them off in batch runs gives a clear speedup.

09 / 09

Summary

SolidWorks Python scripting is the fastest way to test an automation idea. Once the COM bridge is up, the full API is available through SldWorks.Application and IModelDoc2.

Get three things right from the start: think in metres, drive parameters through global variables, and check every result. Without those three, a script that looks like it is working will quietly produce wrong output.

And remember: if the flow you built quickly in Python is going to last, at some point it needs to move to the C# side. That is not a failure — it is a planned step.

Part of this guideSolidWorks Automation — Macros, API and Add-ins — A Complete GuideMacro, API, or add-in? Which layer solves which job, which language to pick, and where to start — gathered on one page.İ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.

Kaynaklar

ShareLinkedIn