Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
812 views
in Technique[技术] by (71.8m points)

com - Saving AutoCAD files (.dwg) using Python

I am using win32com to automate some simple tasks in AutoCAD. It's mostly been working quite well except for being able to save files. My goal is to open a (template) file, adjust it depending on what is needed then save the file as a .dwg in another folder while leaving the template empty and ready to be used next time.

The following in an example of my code:

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()

Loading the template file works well, but when trying to save the file (using the SaveAs method I get the following error:

    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)

Any tips or resources will be much appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Looking at the documentation for the ActiveX API for AutoCAD it looks like when you Call Documents.Open() it should return the opened document and set it as the active document. That said, it looks like that is not what is happening in practice here. The solution for your issue should look something like this:

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()

You can find the documentation here

AutoCAD.Application

Application.Documents

Documents.Open()

Application.ActiveDocument


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...