pythonautocad

Trying to create a group using pyautocad


I am using pyautocad to create drawings in autocad. I am attempting to group items together, but appear to be entering the items in the wrong format.

from pyautocad import Autocad, APoint, aDouble
import win32com.client

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

for doc in acadApp.Documents:
    if doc.Name == "Template.dwg":
        acadApp.ActiveDocument = doc

acad = Autocad()

group_name = "MyGroup"
group = doc.Groups.Add(group_name)

line1 = acad.model.AddLine(APoint(0, 0), APoint(100, 100))
line2 = acad.model.AddLine(APoint(100, 100), APoint(200, 0))

group.AppendItems([line1, line2])

I recieve this error:

File "COMObject Add", line 2, in AppendItems

TypeError: Objects for SAFEARRAYS must be sequences (of sequences), or a buffer object.

I have attempted to change the format to differrent ways suggested by chat gpt, for example:

group.AppendItems([[line1], [line2]])
group.AppendItems(((line1,), (line2,)))

or

for obj in (line1, line2):
    try:
        group.AppendItems([[obj]])  # Each object wrapped as a list inside a list
        print(f"Successfully appended object with Handle: {obj.Handle}")
    except Exception as e:
        print(f"Failed to append object with Handle {obj.Handle}: {e}")

or trying to create a safe array

sa = SafeArrayCreateVector(VT_VARIANT, 0, 2)
SafeArrayPutElement(sa, 0, line1)
SafeArrayPutElement(sa, 1, line2)

# Append the SAFEARRAY to the group
group.AppendItems(sa)

I have ran through every chatgpt response until it gave up.


Solution

  • I was unable to solve this issue, but I found a work around, using send command instead:

    line1 = acad.model.AddLine(APoint(0, 0), APoint(100, 100))
    acad.doc.SendCommand('select ' + 'l  ')
    acad.doc.SendCommand('ai_deselect ')
    
    line2 = acad.model.AddLine(APoint(100, 100), APoint(200, 0))
    acad.doc.SendCommand('select ' + 'p ' + 'l  ')
    acad.doc.SendCommand('group ')
    

    This draws a line, selects it, then deselect. Line 2 is drawn, the previous selection is highlighted (line 1) and then the last thing drawn (line 2). Then sends the group command.