【问题标题】:pysnmp: Reuse iterator to walk several OIDs?pysnmp:重用迭代器来遍历几个 OID?
【发布时间】:2021-04-02 21:06:04
【问题描述】:

我正在使用 pysnmp 来查询多个 oid 范围。我需要使用 nxtCmd 因为这些我需要遍历所有的 IF 地址。但是,当我使用 lexicographicMode=False 来防止在行走时越过 OID 障碍时,我无法重用相同的迭代器来使用“发送”查询新范围,因为我收到了 StopIteration 错误(迭代器已用尽)。每次都实例化一个新的迭代器的解决方案是什么?我是不是在错误地处理这个问题?

代码:

iterator = nextCmd(SnmpEngine(),
                          CommunityData('public'),
                          UdpTransportTarget(('localhost', 161)),
                          ContextData(),
                          ObjectType(ObjectIdentity('1.3.6.1.2.1.4.20.1.1')),
                          lexicographicMode=False)

for (errorIndication,
     errorStatus,
     errorIndex,
     varBinds) in iterator:

    if errorIndication:
        print(errorIndication)
        break
    
    elif errorStatus:
        print('%s at %s' % (errorStatus.prettyPrint(),
                            errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
        break
    
    else:
        for varBind in varBinds:
            print(type(varBind))
            print(' = '.join([x.prettyPrint() for x in varBind]))

errorIndication, errorStatus, errorIndex, varBinds = iterator.send(ObjectType(ObjectIdentity('1.3.6.1.2.1.4.20.1.1')))
print(varBinds[1].prettyPrint)

第一个循环有效,发送命令产生一个 StopIteration 异常

【问题讨论】:

  • 试试itertools.tee

标签: python network-programming snmp pysnmp


【解决方案1】:

是的,如果迭代器用尽了,就不能重用它。

但是,即使是迭代器和generators are similar,也只有生成器支持send 方法。

我会首先检查 nextCmd 是否确实返回了一个生成器,如果是,请查看这篇文章:How to Use .send(),它会给你一个例子。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-03
    • 2012-06-12
    • 2012-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多