Win32com、Python 和 AutoCAD 的变体错误



受到这个答案的启发,我尝试使用python和win32com.client来操作打开的AutoCAD文件,并将给定图层中的所有对象收集到选择集中:

from comtypes.client import *
from comtypes.automation import *
import win32com.client
acad = GetActiveObject("AutoCAD.Application")
doc = acad.ActiveDocument
SSet = doc.SelectionSets[0]
FilterType = win32com.client.VARIANT(VT_ARRAY|VT_I2, [8]) 
FilterData = win32com.client.VARIANT(VT_ARRAY|VT_VARIANT, ["Layer1"])
SSet.Select(5, FilterType, FilterData)

select 命令会轰炸并显示以下错误消息:

ArgumentError: argument 2: <class 'TypeError'>: Cannot put win32com.client.VARIANT(8194, [8]) in VARIANT

我模糊地理解这个错误,因为它抱怨第二个参数的类型/格式(如果它走得那么远,可能是第三个),但我不明白为什么:它似乎告诉我它不能接受想要变体的插槽中的特定变体,但我不知道为什么。

在回答时请记住,我精通python,AutoCAD和老式的AutoLISP编码,但对win32com(或任何其他com),特别是变体或让AutoCAD使用python几乎一无所知。

(对于其他老派:我正在尝试模仿SSGET命令。

就个人而言,我对选择集不是很有经验,所以我偶然发现了一个没有使用它们的解决方案。下面的代码是循环遍历模型空间中的每个对象的示例,检查它是否具有特定的层,并构建一个字符串,该字符串将通过SendCommand选择所有对象。

我相信您实际上也可以使用SendCommand来操作选择集。(类似于 Autolisp 中的(command "ssget"))我个人发现这个解决方案更容易解决。

# I personally had better luck with comtypes than with win32com
import comtypes.client
try:
# Get an active instance of AutoCAD
app = comtypes.client.GetActiveObject('AutoCAD.Application', dynamic=True)
except WindowsError: # No active instance found, create a new instance.
app = comtypes.client.CreateObject('AutoCAD.Application', dynamic=True)
# if you receive dispatch errors on the line after this one, a sleep call can
# help so it's not trying to dispatch commands while AutoCAD is still starting up.
# you could put it in a while statement for a fuller solution
app.Visible = True
doc = app.ActiveDocument
# if you get the best interface on an object, you can investigate its properties with 'dir()'
m = comtypes.client.GetBestInterface(doc.ModelSpace)
handle_string = 'select'
for entity in m:
if entity.Layer == 'Layer1':
handle_string += ' (handent "'+entity.Handle+'")'
handle_string += 'nn'
doc.SendCommand(handle_string)

在 VBA 引用中,签名为:

object.Select Mode[, Point1][, Point2][, FilterType][, FilterData]

试试这个:

SSet.Select(5, None,  None,  FilterType, FilterData)

最新更新