python-3.xattributeswin32comautocadautocad-scripts

Add attributes existing Autocad block with python


I have multiple autocad files with tons of blocks already defined. I would like to write a python script that for each file adds 3 new attributes to each block.

I tried the following code:

import win32com.client
import pandas as pd
from pyautocad import Autocad, aDouble

acad = win32com.client.Dispatch("AutoCAD.Application")

doc = acad.ActiveDocument  # Document object
for entity in acad.ActiveDocument.ModelSpace:
    name = entity.EntityName
    if name == 'AcDbBlockReference':
        HasAttributes = entity.HasAttributes
        if HasAttributes:
            entity.AddAttribute(50, 0, "test", aDouble(200, 100, 0), "TEST", "TEST TEXT")

Even if it should be in the pyautocad library, AddAttribute is not recognized apparently, indeed I receive the

AttributeError: <unknown>.AddAttribute. Did you mean: 'GetAttributes'?

I am not interested in getting attributes, I would like to define new ones. Probably I should use win32com library but i feel lost. Any suggestions to fix it?

UPDATE

Here the correct code:

from pyautocad import Autocad, aDouble

acad = Autocad(create_if_not_exists=True)
doc = acad.ActiveDocument
blocks = acad.ActiveDocument.Blocks
print(blocks.ObjectName, ' number elements: ', blocks.Count)
for block in blocks:
    block.addAttribute((50, 0, "test", aDouble(200, 100, 0), "TEST", "TEST TEXT")

Then, launch ATTSYNC


Solution

  • The AddAttribute method will create an Attribute Definition, which should belong to a Block Definition, not a Block Reference (which is one of potentially many instances of the definition inserted in the drawing at varying positions, scales, rotations & orientations).

    As such, you should obtain the target Block Definition object from the Blocks Collection (acad.ActiveDocument.Blocks) and invoke the AddAttribute method on this container.

    It may also be necessary to 'synchronise' the attributes held by block references with those found in the definition - this operation is performed by the standard ATTSYNC command in AutoCAD.