'Get the running AutoCAD application using comtypes in python 2.7
I'm trying to fetch an instance to point to the already running AutoCAD 2016 application, or to create a new instance if it's not running.
Here's a simple code sample for that:
#Import needed modules
import os
import comtypes.client
from comtypes import COMError
from comtypes.client import CreateObject, GetModule, GetActiveObject
try:
acad = GetActiveObject("AutoCAD.Application.20")
print "AutoCAD is Active"
print "########"
except(OSError, COMError): #If AutoCAD isn't running, run it
acad = CreateObject("AutoCAD.Application.20",dynamic=True)
print "AutoCAD is successfuly Opened"
print "########"
When AutoCAD isn't running, the function CreateObject works successfully & only if dynamic is set to true .. but GetActiveObject throws the Traceback error
File "C:\Python27\lib\site-packages\comtypes\client\__init__.py", line 250, in CreateObject
return _manage(obj, clsid, interface=interface)
File "C:\Python27\lib\site-packages\comtypes\client\__init__.py", line 188, in _manage
obj = GetBestInterface(obj)
File "C:\Python27\lib\site-packages\comtypes\client\__init__.py", line 112, in GetBestInterface
interface = getattr(mod, itf_name)
AttributeError: 'module' object has no attribute 'IAcadApplication'
I've seen this but with no clue.
Also, I've returned to the documentation of comtypes, it says
The GetActiveObject function succeeds when the COM object is already running, and has registered itself in the COM running object table. Not all COM objects do this.
but this also doesn't give me any clue.
P.S GetActiveObject works well with me with other applications such as ETABS 2016 & SAP2000 v18
Any help & insightful responses will be totally appreciated, thanks in advance
Solution 1:[1]
It's weird but it does work (at least with me)
I went to the gen folder, its full path is C:\Python27\Lib\site-packages\comtypes\gen, then looked for the file AutoCAD.py, opened it in IDLE, knew its equivalent generated symbol (ID) such as _4E3F492A_FB57_4439_9BF0_1567ED84A3A9_0_1_0, then deleting these 4 files:
- AutoCAD.py
- AutoCAD.pyc
- _4E3F492A_FB57_4439_9BF0_1567ED84A3A9_0_1_0.py
- _4E3F492A_FB57_4439_9BF0_1567ED84A3A9_0_1_0.pyc
You can notice that the last 2 files are named by the same equivalent generated symbol which is mentioned in the file AutoCAD.py .
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Serag Hassouna |
