Python 调用 SolidWorks API 实现自动化建模示例
近年来,AI 技术逐渐渗透至工作场景。借助 SolidWorks 开放接口与 Python 生态,可实现基础自动化建模。
实现步骤
- 建立 Python 与 SolidWorks 的连接
- 通过代码新建零件文档
- 在前视基准面绘制正八边形
- 对该草图进行拉伸
- 保存生成的零件文件
连接配置
- 找到项目虚拟环境下的 makepy.py。
- 运行后选择 SOLIDWORKS Type library 和 Constant type library。
- 复制生成的 py 文件(如 swconnect 和 swconst)到虚拟环境下 win32com 的 client 目录。
代码实现
import time
import math
import win32com.client
from win32com.client import VARIANT
import pythoncom
swApp = win32com.client.Dispatch("SldWorks.Application")
swApp.Visible = True
time.sleep(2)
# 新建零件
template_path = r"C:\ProgramData\SolidWorks\SOLIDWORKS 2021\templates\gb_part.prtdot"
swModel = swApp.NewDocument(template_path, 0, 0, 0)
if swModel is None:
raise RuntimeError("❌ 新建失败")
print("✅ 成功新建零件文档")
modelView = swModel.ActiveView
if modelView:
modelView.FrameState = 1
swModelExt = swModel.Extension
swSketchMgr = swModel.SketchManager
swFeatMgr = swModel.FeatureManager
arg_null = VARIANT(pythoncom.VT_DISPATCH, None)
# === 正八边形 ===
swModelExt.SelectByID2("Front Plane", "PLANE", 0, 0, 0, False, 0, arg_null, )
swSketchMgr.InsertSketch()
R = / ( * math.sin(math.pi / ))
points = []
i ():
angle = i * ( * math.pi / )
x = R * math.cos(angle)
y = R * math.sin(angle)
points.append((x, y))
i ():
x1, y1 = points[i]
x2, y2 = points[(i + ) % ]
swSketchMgr.CreateLine(x1, y1, , x2, y2, )
swSketchMgr.InsertSketch()
extrude = swFeatMgr.FeatureExtrusion2(, , , , , , , , , , , , , , , , , , , , , , )
extrude :
RuntimeError()
()


