PuppetDb Python 脚本获取事实是否存在?

PuppetDb Python script get fact if exists?

我正在使用 PuppetDb python library。如果事实存在,我想打印它的值。

for group in groups:
  node = puppetdb.node(group[0])
  if hasattr(node.facts, 'custom_fact'):
    print node.fact('custom_fact')

我对 python 比较陌生,但我读到 here 上面的方法应该允许我检查对象是否具有属性。

不确定我是否误解了说明或者 PuppetDb 对象的行为是否不同。

如何仅在 custom_fact 存在时打印它?


编辑:当我使用 print node.facts 时,它说 node.facts 是绑定方法。 所以我也在尝试这个(有 osfamily 事实,因为它应该总是 return 一些东西):

for group in groups:
  node = puppetdb.node(group[0])
  facts = node.facts()
  print facts
  if hasattr(facts, 'osfamily'):
    print facts('osfamily')

print facts returns <generator object facts at 0x7f906ffe35f0>

print node.facts('custom_fact') 永远不会是 运行.

还尝试 dir(facts) 寻找不 return 任何东西的属性,这让我相信这不是一个普通对象。

我发现使用 try/except 效果更好:

for group in groups:
  print group[0]
  node = puppetdb.node(group[0])
  try:
    print node.fact('custom_fact').value
  except:
    pass