排除 Python 中的 COMError

RBu*_*ntu 2 python autocad python-2.7

在 python 中排除 COMError 有困难。下面是我在 AutoCAD 中调用的方法。

    def populate_drawing(self):
        nMeasurementsFinal = Feature_recognition.determine_OD_dims(Feature_recognition(), "C:\\Users\\buntroh\\Documents\\Rotoworks\\122508.csv")
        while True:
            try:
                for nObject in self.acad.iter_objects(None, None, None, False):
                    if hasattr(nObject, 'TextString'):
                        try:
                            nObject.TextString = nMeasurementsFinal[nObject.TextString]
                        except KeyError as e:
                            continue
            except COMError:
                self.acad.doc.SendCommand("Chr(3)")
            break
Run Code Online (Sandbox Code Playgroud)

COMError 异常是因为只要在运行脚本之前在 AutoCAD 中选择了某些内容,它就会返回 COMError。但是,即使有例外,我仍然得到:

COMError: (-2147418111, 'Call was rejected by callee.', (None, None, None, 0, None))
Run Code Online (Sandbox Code Playgroud)

当没有选择任何内容并且脚本不必处理 COMError 异常时,我得到:

NameError: global name 'COMError' is not defined
Run Code Online (Sandbox Code Playgroud)

不知道该怎么办。我导入了comtypes,所以我不确定为什么 COMError 未定义。

Iam*_*lie 5

同意上述评论之一,您需要

from comtypes import COMError
Run Code Online (Sandbox Code Playgroud)

那么你的异常可能是这样的假设错误:COMError: (-2147418111, 'Call was denied by callee.', (None, None, None, 0, None))

except COMError as ce:
    target_error = ce.args # this is a tuple
    if target_error[1] == 'Call was rejected by callee.':
        self.acad.doc.SendCommand("Chr(3)")
Run Code Online (Sandbox Code Playgroud)