I need to connect and control AutoCAD via COM interface. For this purpose, I use Python. In my first trial with a very basic snippet(1), I got an error. The code is:
import win32com.client
acad = win32com.client.Dispatch("AutoCAD.Application")
doc = acad.ActiveDocument
doc.Utility.Prompt("Hello from Python\n")
and when I try to run it, I get this:
Traceback (most recent call last):
File "C:\Users\SBYSMR10\Desktop\recipe-440493-1.py", line 2, in <module>
acad = win32com.client.Dispatch("AutoCAD.Application")
File "C:\Python26\lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch
dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 108, in _GetGoodDispatchAndUserName
return (_GetGoodDispatch(IDispatch, clsctx), userName)
File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 85, in _GetGoodDispatch
IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch)
com_error: (-2147221005, 'Invalid class string', None, None)
I have Python 2.6 and AutoCAD LT 2009 installed. I searched through the net for a solution but couldn't find any. So could you help me fix this issue?
(1) Code taken from @Tom Haws' blog.
AutoCAD LT versions doesn't support automation (discussion in Autodesk group).
If you'll be able to install full AutoCAD version, I'd suggest you to use
comtypes
package. Withwin32com
you can't add entities to document, because AutoCAD requires VARIANTs with the typecodesVT_ARRAY | VT_I2 or VT_ARRAY | VT_R8
for parameters, e.g.InsertionPoint
.See examples in
comtypes
documentation