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

标签 python com win32com autocad autocad-plugin

我正在使用 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() 时,它应该返回打开的文档并将其设置为事件文档。也就是说,实际情况似乎并非如此。您的问题的解决方案应如下所示:

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

关于python - 使用 Python 保存 AutoCAD 文件 (.dwg),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58450655/

相关文章:

python - pandas : pandas. io.common.CParserError 错误:标记数据时出错

python - 不要使用 tf.reset_default_graph() 清除嵌套图

Python Click 命令无法识别选项

python - 如何根据值更改Excel单元格颜色?

linux - 在 virtual_env 中使用 pyinstaller 时出现 win32com 错误

python - 如何使用 Python OpenCV 定义阈值以仅检测图像中的绿色对象?

.net - 免注册COM可以应用于DLL吗?

Windows COM : generic byte array sink

Python:在没有剪贴板的情况下从 Office/Excel 文档访问嵌入式 OLE

python - 使用Python在word中查找和替换脚注