pythonwin32comautocaddwg

How to iterate through the entities of an AutoCAD drawing?


I want to automate the processing of a set of AutoCAD files using Python and the COM interface. To that end I need to iterate through the entities of each drawing. So far I have been able to get the job done by using pyautocad.

import win32com.client
from pyautocad import Autocad
import os

folder = r'C:\path\to\my\folder'
filename = 'my_file.dwg'
drawing_file = os.path.join(folder, filename)

acad32 = win32com.client.dynamic.Dispatch("AutoCAD.Application")
doc = acad32.Documents.Open(drawing_file)

acadpy = Autocad() 

entities = [acadpy.best_interface(obj) for obj in  acadpy.iter_objects()] 

Is there any way to iterate through the drawing entities whithout using pyautocad? More specifically, I'm looking for something like this:

entities = [obj for obj in  acad32.Objects] 

Apparently acad32 does not have any attributes similar to Object, Entities or whatever that might be useful to solve my problem:

In [239]: doc.__dict__
Out[239]: 
{'_oleobj_': <PyIDispatch at 0x00000281D7C162E0 with obj at 0x00000281D79D9298>,
 '_username_': 'Open',
 '_olerepr_': <win32com.client.build.LazyDispatchItem at 0x281da18f1d0>,
 '_mapCachedItems_': {},
 '_builtMethods_': {},
 '_enum_': None,
 '_unicode_to_string_': None,
 '_lazydata_': (<PyITypeInfo at 0x00000281D7C16580 with obj at 0x00000281D7C08648>,
  <PyITypeComp at 0x00000281D7C16310 with obj at 0x00000281D7C08808>)}

Solution

  • Assuming that you want to iterate over the objects residing in Modelspace, you might try something along the following lines:

    for obj in doc.Modelspace
    

    If you need to iterate over all objects in all layous (not just Modelspace), you could use:

    for lyt in doc.Layouts
        for obj in lyt.Block
    

    Or, if you need to iterate over all objects in all layouts & blocks (including external references), you could use:

    for blk in doc.Blocks
        for obj in blk
    

    This is untested of course and assumes that all of these properties are exposed to the Win32 COM interface.

    The official AutoCAD ActiveX reference may be found here.