0
0
Arm-architectureHow-ToBeginner · 4 min read

How to Automate SolidWorks Using Python: Simple Guide

You can automate SolidWorks using Python by controlling its COM API with the pywin32 library. This lets you open files, create parts, and run commands programmatically by connecting to SolidWorks as a COM object.
📐

Syntax

To automate SolidWorks with Python, you use the win32com.client.Dispatch function to create a SolidWorks application object. Then you call methods on this object to control SolidWorks.

  • Dispatch('SldWorks.Application'): Connects to SolidWorks.
  • swApp.Visible = True: Makes SolidWorks visible.
  • swApp.OpenDoc(file_path, doc_type): Opens a document.
  • swApp.NewPart(): Creates a new part document.
python
import win32com.client

swApp = win32com.client.Dispatch('SldWorks.Application')
swApp.Visible = True

# Open a part document
part = swApp.OpenDoc('C:\\Path\\To\\Part.SLDPRT', 1)  # 1 = Part document
💻

Example

This example shows how to start SolidWorks, create a new part, and save it using Python automation.

python
import win32com.client
import time

# Connect to SolidWorks
swApp = win32com.client.Dispatch('SldWorks.Application')
swApp.Visible = True

# Create a new part document
part = swApp.NewPart()

# Wait a moment for SolidWorks to process
time.sleep(2)

# Save the new part
file_path = 'C:\\Temp\\NewPart.SLDPRT'
swApp.ActiveDoc.SaveAs(file_path)

print(f'New part created and saved at {file_path}')
Output
New part created and saved at C:\Temp\NewPart.SLDPRT
⚠️

Common Pitfalls

Common mistakes when automating SolidWorks with Python include:

  • Not running Python with administrator rights, which can block COM access.
  • Using incorrect document type codes (e.g., 1 for part, 2 for assembly).
  • Forgetting to make SolidWorks visible, so automation runs but you see no window.
  • Not handling file paths correctly (use double backslashes or raw strings).

Always check if SolidWorks is installed and licensed on your machine before running automation scripts.

python
import win32com.client

# Wrong: missing visibility
swApp = win32com.client.Dispatch('SldWorks.Application')
# No swApp.Visible = True, SolidWorks runs hidden

# Right:
swApp.Visible = True
📊

Quick Reference

ActionPython MethodDescription
Start SolidWorkswin32com.client.Dispatch('SldWorks.Application')Connect to SolidWorks COM API
Make VisibleswApp.Visible = TrueShow SolidWorks window
Open PartswApp.OpenDoc(file_path, 1)Open a part document
Create New PartswApp.NewPart()Create a new part document
Save DocumentswApp.ActiveDoc.SaveAs(file_path)Save the active document

Key Takeaways

Use the pywin32 library to control SolidWorks via its COM API from Python.
Always set swApp.Visible = True to see SolidWorks during automation.
Use correct document type codes: 1 for parts, 2 for assemblies, 3 for drawings.
Handle file paths carefully with double backslashes or raw strings in Python.
Run Python with proper permissions to avoid COM access issues.