Win32com、Python和AutoCAD的变量错误

2024-09-29 19:33:07 发布

您现在位置:Python中文网/ 问答频道 /正文

this answer的启发,我正在尝试使用python和win32com客户端要操作打开的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命令。)


Tags: fromimport命令clientdocarraywin32comvariant
1条回答
网友
1楼 · 发布于 2024-09-29 19:33:07

就我个人而言,我对选择集不是很有经验,所以我偶然发现了一个没有使用它们的解决方案。下面的代码是在模型空间中的每个对象之间循环的示例,检查它是否有特定的层,并构建一个字符串,该字符串将通过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 += '\n\n'
doc.SendCommand(handle_string)

相关问题 更多 >

    热门问题