杰瑞科技汇

Python如何与SolidWorks交互?

Of course! Using Python with SolidWorks is a powerful and common task for automating design, analysis, and data management workflows. The primary way to do this is through SOLIDWORKS API (Application Programming Interface), which allows external applications (like Python scripts) to control SolidWorks.

Python如何与SolidWorks交互?-图1
(图片来源网络,侵删)

Here’s a comprehensive guide covering the concepts, tools, and a practical example.


The Core Concept: The SOLIDWORKS API

The SOLIDWORKS API is a set of objects, methods, and properties that you can use to programmatically interact with a SolidWorks session. Think of it as giving your Python script the ability to "press buttons," "fill in dialog boxes," and "read data" from within SolidWorks.

  • Objects: These are the "things" in SolidWorks, like ModelDoc (a part, assembly, or drawing), Feature, Sketch, Body, etc.
  • Methods: These are the "actions" you can perform on objects, like Feature.Extrude2(), Sketch.InsertCurve(), or Model.ForceRebuild().
  • Properties: These are the "attributes" of an object, like Feature.Name, Model.MaterialPropertyName, or Sketch.IsFullyDefined.

Essential Tools & Setup

Before you write any code, you need to set up your environment.

A. pywin32 (The Bridge)

Python needs a way to communicate with the Windows-based SolidWorks application. The pywin32 library provides this bridge. It allows Python to act as a COM (Component Object Model) client.

Python如何与SolidWorks交互?-图2
(图片来源网络,侵删)

Installation:

pip install pywin32

B. The SOLIDWORKS Type Library (IntelliSense)

To get autocompletion (IntelliSense) in your IDE (like VS Code or PyCharm), you need to reference the SolidWorks type library. This tells Python what objects, methods, and properties are available.

How to Add the Reference:

  1. Open Python in an environment where SolidWorks is installed.
  2. Run the following Python code. This will register the type library with Python's win32com module.
import pythoncom
import win32com.client
# This line registers the SOLIDWORKS type library for use with pywin32
# You only need to run this once per machine.
win32com.client.gencache.EnsureDispatch("SldWorks.Application")

After running this, a gen_py folder will be created in your Python site-packages, containing the type information. Now your IDE will be able to provide helpful hints.

Python如何与SolidWorks交互?-图3
(图片来源网络,侵删)

C. Starting SolidWorks

You have two main ways to start SolidWorks from your script:

  1. Attach to an Existing Session: Your script will connect to a copy of SolidWorks that is already open. This is great for interactive work.
  2. Launch a New Session: Your script will start a new, hidden instance of SolidWorks in the background. This is ideal for automated, non-interactive tasks (like batch processing).

A Simple Python Script: The "Hello, World!" of SOLIDWORKS Automation

Let's write a script that connects to SolidWorks, creates a new part, adds a simple extrude feature, and saves it.

import os
import win32com.client
# --- Configuration ---
# Define where to save the new part
output_dir = r"C:\Temp\SolidWorksPython" # Use a raw string (r"") for paths
if not os.path.exists(output_dir):
    os.makedirs(output_dir)
output_path = os.path.join(output_dir, "MySimplePart.SLDPRT")
# --- Main Script ---
try:
    # 1. Connect to or launch SolidWorks
    # Use Dispatch to connect to an existing session
    # Use 'new' to launch a new, hidden session
    sw_app = win32com.client.Dispatch("SldWorks.Application")
    # Make SolidWorks visible (optional, good for debugging)
    # If you launched a new session, you might want to see it.
    sw_app.Visible = True
    # 2. Get a model document object
    # We'll create a new part document
    new_part_doc = sw_app.NewDocument(r"C:\Program Files\SOLIDWORKS Corp\SOLIDWORKS\samples\tutorial\api\part_primitives.SLDPRT", 0, 0, 0)
    # Get the model from the active document
    model = sw_app.ActiveDoc
    # 3. Get the feature manager and body manager
    feat_mgr = model.FeatureManager
    body_mgr = model.BodyManager
    # 4. Create a simple sketch on the Front Plane
    # Get the plane by its name
    front_plane = model.Extension.GetEntityByName("Front Plane", 0)
    # Create a new sketch
    sketch = model.SketchManager.CreateSketch(True, front_plane)
    # Draw a simple rectangle
    # SketchManager.CreateRectangle(x1, y1, z1, x2, y2, z2)
    sketch.InsertCurve([0, 0, 0, 0.1, 0, 0, 0.1, 0.1, 0, 0, 0.1, 0])
    # 5. Create an extrude feature
    # FeatureManager.FeatureExtrusion2(True, False, False, 0, 0, 0.05, 0.05, False, False, False, False, 0, 0, False, False, False, False, False, False, False, False, 0)
    feat_mgr.FeatureExtrusion2(True, False, False, 0, 0, 0.05, 0.05, False, False, False, False, 0, 0, False, False, False, False, False, False, False, False, 0)
    # 6. Save and Close the document
    model.SaveAs(output_path)
    print(f"Part saved successfully to: {output_path}")
    # You can also rebuild the model to ensure everything is up-to-date
    model.ForceRebuild3(True)
except Exception as e:
    print(f"An error occurred: {e}")
finally:
    # 7. Clean up (important for background processes)
    # Release the objects
    if 'model' in locals():
        model = None
    if 'sw_app' in locals():
        sw_app = None
    # If you launched a hidden session, you might want to quit it.
    # sw_app.ExitApp()

Best Practices and Important Considerations

A. The Macro Recorder is Your Best Friend

SolidWorks has a built-in macro recorder (Tools > Macro > Record). It records your mouse clicks and actions into a VBA macro. You can then open the VBA editor (Tools > Macro > Edit), look at the generated code, and translate it into Python. This is the fastest way to learn the API for a specific task.

Example VBA Code (from Macro Recorder):

Sub main()
    Dim swApp As SldWorks.SldWorks
    Dim swModel As SldWorks.ModelDoc2
    Dim swSelMgr As SldWorks.SelectionMgr
    Set swApp = Application.SldWorks
    Set swModel = swApp.ActiveDoc
    Set swSelMgr = swModel.SelectionManager
    ' Select a face
    swSelMgr.SetSelect2 1, -1, False, 0, Nothing, 0
    ' Insert a new extrude
    Dim boolstatus As Boolean
    Dim feat As SldWorks.Feature
    Set feat = swModel.FeatureManager.FeatureExtrusion2(True, False, False, 0, 0, 0.01, 0.01, False, False, False, False, 0, 0, False, False, False, False, False, False, False, False, 0)
End Sub

You can easily see how the VBA FeatureExtrusion2 method maps to the Python feat_mgr.FeatureExtrusion2() call.

B. Error Handling

Always wrap your API calls in try...except blocks. The API can raise errors for many reasons (e.g., a feature fails, a file is missing, a selection is invalid). The win32com library often converts these into standard Python COM exceptions.

C. Performance and Background Mode

For tasks that don't require user interaction (like generating hundreds of configurations or running simulations), always run SolidWorks in hidden mode.

# Launch a hidden session
sw_app = win32com.client.Dispatch("SldWorks.Application")
sw_app.Visible = False # This is the key line
# ... do work ...
# Quit the application when done
sw_app.ExitApp()

This is much faster and doesn't require a SolidWorks license to be active for a user on the machine.

D. Documentation

The official SOLIDWORKS API Help is the ultimate resource. You can find it under Help > API Help in SolidWorks. It details every object, method, and property with examples.


Popular Python Wrappers

While using the raw pywin32 API is powerful, it can be verbose. Some developers have created Python wrappers to simplify common tasks.

  • PySW: A lightweight wrapper that simplifies some API calls.
  • SOLIDWORKS PDM API: A separate API for managing files in the PDM vault. It also uses pywin32 but has its own set of objects.
  • Custom Scripts: Many companies build their own internal libraries of helper functions to standardize their automation scripts.

Summary: Getting Started

  1. Install pywin32: pip install pywin32
  2. Register the Type Library: Run the gencache.EnsureDispatch line once.
  3. Use the Macro Recorder: Record a simple action in SolidWorks and look at the VBA code to understand the API calls.
  4. Write a Simple Script: Start with connecting, opening a document, and saving it.
  5. Iterate: Gradually add more complex features like creating sketches, adding features, and modifying properties.
  6. Adopt Best Practices: Use error handling and hidden mode for batch operations.
分享:
扫描分享到社交APP
上一篇
下一篇