Python可以通过多种方式操作CAD文件(如DWG、DXF等格式),以下是几种主要方法和实现代码。

1. 使用pyautocad库(针对AutoCAD)

安装

pip install pyautocad comtypes

基本操作示例

from pyautocad import Autocad, APoint

# 连接到AutoCAD
acad = Autocad(create_if_not_exists=True)

# 在模型空间添加文本
acad.model.AddText("Hello AutoCAD!", APoint(0, 0), 2.5)

# 画线
p1 = APoint(0, 0)
p2 = APoint(10, 10)
acad.model.AddLine(p1, p2)

# 画圆
center = APoint(5, 5)
radius = 3
acad.model.AddCircle(center, radius)

# 获取所有对象
for obj in acad.iter_objects():
    print(obj.ObjectName)

2. 使用ezdxf库(操作DXF文件)

安装

pip install ezdxf

创建和读取DXF文件

import ezdxf

# 创建新DXF文档
doc = ezdxf.new('R2010')  # 使用AutoCAD 2010 DXF格式
msp = doc.modelspace()

# 添加实体
msp.add_line((0, 0), (10, 10))
msp.add_circle((5, 5), radius=3)
msp.add_text("Hello DXF!", dxfattribs={'height': 0.5, 'insert': (2, 2)})

# 保存文件
doc.saveas("example.dxf")

# 读取DXF文件
doc = ezdxf.readfile("example.dxf")
msp = doc.modelspace()

# 遍历所有实体
for entity in msp:
    print(f"类型: {entity.dxftype()}, 数据: {entity.dxf}")

3. 使用pythoncom与AutoCAD交互(Windows)

import win32com.client

# 启动AutoCAD
acad = win32com.client.Dispatch("AutoCAD.Application")
acad.Visible = True  # 使AutoCAD可见

# 获取当前文档
doc = acad.ActiveDocument

# 获取模型空间
model_space = doc.ModelSpace

# 添加直线
start_point = win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_R8, (0, 0, 0))
end_point = win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_R8, (10, 10, 0))
line = model_space.AddLine(start_point, end_point)

# 添加圆
center = win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_R8, (5, 5, 0))
radius = 3
circle = model_space.AddCircle(center, radius)

# 缩放视图
doc.Application.ZoomAll()

4. 使用PyDrafter(轻量级2D CAD)

安装

pip install pydrafter

示例代码

from pydrafter import Document

# 创建新文档
doc = Document()

# 添加图层
doc.add_layer("main", color="#FF0000")

# 添加实体
doc.add_line((0, 0), (10, 10), layer="main")
doc.add_circle((5, 5), 3, layer="main")

# 保存为DXF
doc.save("output.dxf")

# 显示预览(需要matplotlib)
doc.preview()

5. 使用CAD转换库(处理DWG等格式)

安装

pip install cadquery

示例代码

import cadquery as cq

# 创建简单3D模型
result = cq.Workplane("XY").box(10, 10, 2).faces(">Z").hole(5)

# 导出为STEP文件
result.val().exportStep("box_with_hole.step")

# 显示模型(需要安装Jupyter)
show_object(result)

6. 使用PyOpenGL显示CAD模型

安装

pip install PyOpenGL PyOpenGL_accelerate

简单3D显示示例

from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *

def draw():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glLoadIdentity()
    
    # 绘制坐标系
    glBegin(GL_LINES)
    glColor3f(1, 0, 0)  # X轴红色
    glVertex3f(0, 0, 0)
    glVertex3f(5, 0, 0)
    
    glColor3f(0, 1, 0)  # Y轴绿色
    glVertex3f(0, 0, 0)
    glVertex3f(0, 5, 0)
    
    glColor3f(0, 0, 1)  # Z轴蓝色
    glVertex3f(0, 0, 0)
    glVertex3f(0, 0, 5)
    glEnd()
    
    # 绘制一个立方体
    glColor3f(1, 1, 1)
    glutWireCube(2)
    
    glutSwapBuffers()

def main():
    glutInit()
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
    glutInitWindowSize(800, 600)
    glutCreateWindow(b"CAD 3D Viewer")
    
    glEnable(GL_DEPTH_TEST)
    glMatrixMode(GL_PROJECTION)
    gluPerspective(45, 800/600, 0.1, 50.0)
    glMatrixMode(GL_MODELVIEW)
    glTranslatef(0, 0, -5)
    
    glutDisplayFunc(draw)
    glutIdleFunc(draw)
    glutMainLoop()

if __name__ == "__main__":
    main()

综合CAD文件查看器(使用ezdxf和matplotlib)

import ezdxf
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, Rectangle, Polygon
from matplotlib.collections import PatchCollection
import numpy as np

class DXFViewer:
    def __init__(self, filepath):
        self.doc = ezdxf.readfile(filepath)
        self.msp = self.doc.modelspace()
        self.fig, self.ax = plt.subplots(figsize=(10, 10))
        
    def draw_entities(self):
        patches = []
        
        for entity in self.msp:
            if entity.dxftype() == 'LINE':
                x = [entity.dxf.start[0], entity.dxf.end[0]]
                y = [entity.dxf.start[1], entity.dxf.end[1]]
                self.ax.plot(x, y, 'b-')
                
            elif entity.dxftype() == 'CIRCLE':
                circle = Circle((entity.dxf.center[0], entity.dxf.center[1]), 
                              entity.dxf.radius, fill=False)
                patches.append(circle)
                
            elif entity.dxftype() == 'LWPOLYLINE':
                points = entity.get_points('xy')
                polygon = Polygon(points, closed=True, fill=False)
                patches.append(polygon)
                
            elif entity.dxftype() == 'INSERT':  # 块引用
                self.draw_block(entity)
                
        if patches:
            collection = PatchCollection(patches, match_original=True)
            self.ax.add_collection(collection)
    
    def draw_block(self, insert):
        block = self.doc.blocks[insert.dxf.name]
        base_point = insert.dxf.insert
        
        for entity in block:
            if entity.dxftype() == 'LINE':
                start = np.array(entity.dxf.start) + np.array(base_point)
                end = np.array(entity.dxf.end) + np.array(base_point)
                self.ax.plot([start[0], end[0]], [start[1], end[1]], 'b-')
                
            elif entity.dxftype() == 'CIRCLE':
                center = np.array(entity.dxf.center) + np.array(base_point)
                circle = Circle((center[0], center[1]), entity.dxf.radius, fill=False)
                self.ax.add_patch(circle)
    
    def show(self):
        self.draw_entities()
        self.ax.set_aspect('equal')
        self.ax.autoscale()
        plt.title("DXF Viewer")
        plt.xlabel("X")
        plt.ylabel("Y")
        plt.grid(True)
        plt.show()

# 使用示例
if __name__ == "__main__":
    viewer = DXFViewer("example.dxf")
    viewer.show()

注意事项

  1. AutoCAD交互

    • pyautocadwin32com需要安装AutoCAD软件

    • 确保AutoCAD的COM接口已启用

  2. DWG文件支持

    • 纯Python库通常只支持DXF格式

    • 处理DWG需要商业库如Teigha File ConverterODA SDK

  3. 性能考虑

    • 复杂CAD文件可能包含大量实体,处理时注意内存使用

    • 对于大型文件,考虑分批处理

  4. 3D显示

    • 完整3D CAD可视化需要专业库如VTK或Three.js

    • 简单预览可以使用matplotlib或PyOpenGL

综合对比表

方法 支持格式 需要CAD软件 平台支持 适合场景 学习难度 功能完整性
pyautocad DWG/DXF ✓ (AutoCAD) Windows AutoCAD自动化 ★★★★★
ezdxf DXF 跨平台 DXF文件处理 ★★★★☆
win32com DWG/DXF ✓ (AutoCAD) Windows 高级AutoCAD控制 ★★★★★
PyDrafter 自定义 跨平台 简单2D绘图生成 ★★☆☆☆
CadQuery STEP/STL 跨平台 参数化3D设计 中高 ★★★★☆
PyOpenGL 跨平台 自定义CAD渲染 ★★☆☆☆

选择建议

  1. 需要处理现有DWG文件

    • 商业方案:使用 Teigha File Converter(Python绑定)

    • 免费方案:通过AutoCAD的 pyautocad 或 win32com 导出为DXF后再用 ezdxf 处理

  2. 只需读写DXF文件

    • 首选 ezdxf(功能全面,无依赖)

  3. 参数化3D建模

    • 使用 CadQuery 或 PythonOCC

  4. 跨平台可视化

    • 导出为STEP/STL后,用 PyVista 或 matplotlib 显示

  5. 与AutoCAD深度集成

    • Windows:pyautocad

    • 跨平台:通过AutoCAD的 COM 接口 + Windows虚拟机

性能补充

  • 大文件处理ezdxf 的 streaming 模式可高效处理GB级DXF

  • 批量操作win32com 的 SendCommand 比Python API更快

  • 3D渲染VTK(PyVista)性能远优于 matplotlib

进阶方向

  1. CAD文件转换:实现DWG到DXF、PDF等的转换

  2. 参数化设计:使用CadQuery或PythonOCC创建参数化模型

  3. CAD数据分析:提取尺寸、面积、体积等工程数据

  4. 自动化出图:批量生成工程图纸和BOM表

  5. Web可视化:使用Three.js在浏览器中显示CAD模型

以上方法覆盖了从简单的DXF文件操作到完整的AutoCAD自动化控制,可以根据具体需求选择适合的方案。

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐