我正在枚举列表中的一些对象,这些对象可能具有也可能不具有某些属性。如果属性不存在,我会得到 AttributeError
。我想要做的是捕获异常对象并检索导致错误的特定属性并将其设置为空字符串。我在 AttributeError
对象中没有看到任何方法来检索所述属性。
部分代码在这里:
import wmi
c = wmi.WMI ()
for account in c.Win32_Account():
try:
print(f"Name: {account.Name}, FullName: {account.FullName}, LocalAccount: {account.LocalAccount}, Domain: {account.Domain}")
except AttributeError as error:
# How do I retreive the attribute in question from the exception object?
答案 0 :(得分:0)
根据原始帖子,您希望“检索导致错误的特定属性并将其设置为空字符串”。
如果您只想打印字符串,请使用 getattr:
https://docs.python.org/3/library/functions.html#getattr
import wmi
c = wmi.WMI ()
for account in c.Win32_Account():
print(f"Name: {getattr(account, 'Name', "")}, FullName: {getattr(account, 'FullName', "")}, LocalAccount: {getattr(account, 'LocalAccount', "")}, Domain: {getattr(account, 'Domain', "")}")
如果您想真正覆盖缺失值,请使用 hasattr 和 setattr:
for account in c.Win32_Account():
for attr in ['Name', 'FullName', 'LocalAccount', 'Domain']:
if not hasattr(account, attr):
setattr(account, attr, "")
答案 1 :(得分:-1)
每个 Exception
对象都将其参数存储在 .args
属性中。 AttributeError
对象的参数是一个字符串,其中包含使用属性访问的对象和属性 访问。
此消息的格式如下-
('|")object_name('|") object has no attribute ('|")property_name('|")
其中 ('|")
表示“匹配双引号或单引号”
您可以使用此正则表达式提取对象名称和属性名称-
(?:\'|")(\w+)(?:\'|")
所以最终的实现看起来像-
import wmi
import re
c = wmi.WMI ()
for account in c.Win32_Account():
try:
print(f"Name: {account.Name}, FullName: {account.FullName}, LocalAccount: {account.LocalAccount}, Domain: {account.Domain}")
except AttributeError as error:
property_name = re.findall(r'(?:\'|")(\w+)(?:\'|")', error.args[0])[-1]