Python SolidWorks 二次开发—SolidWorks四种遍历零部件的方式(二)
前言
零部件的遍历主要是为了方便对零部件的后续操作,例如批量零部件的属性修改,方程式修改等,这里介绍四种SolidWorks自带的遍历方法,本文介绍第二种遍历方式,第一种遍历链接方式如下
Python SolidWorks 二次开发—SolidWorks四种遍历零部件的方式(一)
一、官方示例的遍历代码
第二种遍历方法是通过遍历特征,然后找到部组件,SolidWorks 示例中没有直接可用的代码,以下是示例代码(VBA),此方法遍历的原理是通过遍历零部件的特征的方式来实现的,当特征名称为“Reference”或者是“ReferencePattern”时即为零部件,然后提取零部件名称,如果是组件的形式继续递归,直至完成所有遍历
Option Explicit
Sub TraverseComponent(swModel As SldWorks.ModelDoc2, nLevel As Long)
Dim swfeat As SldWorks.Feature
Dim swComp As SldWorks.Component2
Dim compModel As SldWorks.ModelDoc2
Dim sPadStr As String
Dim i As Long
For i = 0 To nLevel - 1
sPadStr = sPadStr + " "
Next i
Set swfeat = swModel.FirstFeature
While Not swfeat Is Nothing
Set swComp = swModel.GetComponentByName(swfeat.Name)
If Not swComp Is Nothing Then
Debug.Print sPadStr & swComp.Name2
If swComp.IsSuppressed = False Then
Set compModel = swComp.GetModelDoc2
If compModel.GetType = 2 Then
TraverseComponent compModel, nLevel + 1
End If
End If
End If
Set swfeat = swfeat.GetNextFeature
Wend
End Sub
Sub main()
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Debug.Print "File = " & swModel.GetPathName
TraverseComponent swModel, 1
End Sub
二、Python遍历代码
此处为方便后续比较,Python代码功能和VBA代码功能保持一致,不进行删减,以下为Python代码示例,Python代码基本和VBA代码一致,修改为对应的Python语法即可,Python可实现对象转换,实现起来更简洁
import win32com.client
import pythoncom
from swconst import constants
def TraverseComponent(swModel, nLevel):
sPadStr=''
for i in range(nLevel-1):
sPadStr = sPadStr + " "
swfeat = swModel.FirstFeature
while swfeat is not None:
swComp=swModel.GetComponentByName(swfeat.Name)
if swComp is not None:
print(f"{
sPadStr}{
swComp.Name2}")
if swComp.IsSuppressed == False:
compModel = swComp.GetModelDoc2
if compModel.GetType == 2:
TraverseComponent(compModel, nLevel + 1)
swfeat = swfeat.GetNextFeature
def main():
sldver=2018
swApp=win32com.client.Dispatch(f'SldWorks.Application.{
sldver-1992}')
swApp.CommandInProgress =True
swApp.Visible =True
errors=win32com.client.VARIANT(pythoncom.VT_BYREF | pythoncom.VT_I4, -1)
warnings=win32com.client.VARIANT(pythoncom.VT_BYREF | pythoncom.VT_I4, -1)
swModel = swApp.ActiveDoc
print(f"File = {
swModel.GetPathName}" )
TraverseComponent(swModel, 1)
if __name__ == '__main__':
main()