我有一段代码在AutoCAD中搜索包含某些关键字的文本框(例如,"overall_weight"在这种情况下),并用字典中的值替换它.但是,有时字典键被分配给空字符串,有时,键不会完全存在.在这些情况下,"overall_weight"关键字应替换为"N/A".我想知道是否有一种更加pythonic的方式来组合KeyError异常和else两者都去,nObject.TextString = "N/A"所以它没有输入两次.
if nObject.TextString == "overall_weight":
try:
if self.var.jobDetails["Overall Weight"]:
nObject.TextString = self.var.jobDetails["Overall Weight"]
else:
nObject.TextString = "N/A"
except KeyError:
nObject.TextString = "N/A"
Run Code Online (Sandbox Code Playgroud)
编辑:为了澄清未来的访问者,我只需要处理3个案例,正确的答案可以处理所有3个案例而不需要任何额外的填充.
dict[key]存在并指向非空字符串.TextString替换为分配给的值dict[key].
dict[key]存在并指向空字符串.TextString换成了"N/A".
dict[key]不存在.TextString换成了"N/A".
在 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 未定义。