pythonwin32comautocadautolispdwg

Check available layers in .dwg file


I need to programmatically check whether a layer exists in an AutoCAD drawing. I am aware that it is straightforward to get the job done using a .dxf, like this:

In [77]: import win32com.client
    ...: import ezdxf
    ...: import os

In [78]: folder = r'C:\path\to\my\folder'
    ...: filename = 'my_file'

In [79]: dxf_path = os.path.join(folder, filename + '.dxf')

In [80]: dxf = ezdxf.readfile(dxf_path)

In [81]: '0' in dxf.layers
Out[81]: True

But what if I want to check the available layers on a .dwg file? I made this attempt, which did not work because the SendCommand method returns None:

In [82]: acad = win32com.client.dynamic.Dispatch("AutoCAD.Application")

In [83]: dwg_path = os.path.join(folder, filename + '.dwg')

In [84]: dwg = acad.Documents.Open(dwg_path)

In [85]: dwg.SendCommand('(tblsearch "layer" "0") ') is not None
Out[85]: False

Any suggestions on how to approach this problem would be greatly appreciated.


Solution

  • You can test whether the following returns a layer object or an exception:

    dwg.Layers.Item('0')
    

    Or alternatively, iterate over all Layer objects within the Layers collection and set a flag variable or return if the Name property of the Layer matches the name of the layer that you seek.