使用 Python 保存 AutoCAD 文件 (.dwg)

Saving AutoCAD files (.dwg) using Python

我正在使用 win32com 在 AutoCAD 中自动执行一些简单的任务。除了能够保存文件外,它大部分都运行良好。我的目标是打开一个(模板)文件,根据需要对其进行调整,然后将文件另存为 .dwg 在另一个文件夹中,同时将模板留空以备下次使用。

以下是我的代码示例:

import win32com.client


acad = win32com.client.dynamic.Dispatch("AutoCAD.Application")
acad.Visible=True

doc = acad.Documents.Open("C:\Template_folder\Template.dwg")
doc.SaveAs("C:\Output_folder\Document1.dwg")

### Adjust dwg ###

doc.Save()

加载模板文件效果很好,但是在尝试保存文件时(使用 SaveAs method 我收到以下错误:

    doc.SaveAs("C:\Output_folder\Document1.dwg")
  File "<COMObject Open>", line 3, in SaveAs
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'AutoCAD', 'Error saving the document', 'C:\Program Files\Autodesk\AutoCAD 2019\HELP\OLE_ERR.CHM', -2145320861, -2145320861), None)

任何提示或资源将不胜感激!

查看 AutoCAD 的 ActiveX API 文档,当您调用 Documents.Open() 时,它应该 return 打开的文档并将其设置为活动文档。也就是说,看起来这不是这里实际发生的事情。您的问题的解决方案应如下所示:

import win32com.client

acad = win32com.client.dynamic.Dispatch("AutoCAD.Application")
acad.Visible=True

# Open a new document and set it as the active document
acad.Documents.Open("C:\Template_folder\Template.dwg")

# Set the active document before trying to use it
doc = acad.ActiveDocument

# Save the documet
doc.SaveAs("C:\Output_folder\Document1.dwg")

### Adjust dwg ###

doc.Save()

您可以在此处找到文档

AutoCAD.Application

Application.Documents

Documents.Open()

Application.ActiveDocument