我不知道如何从代码示例中访问varBinds。我可以打印它,但如果我想存储它或传递给方法或类呢
即使我把它存储在课堂上,我也无法进一步访问它
class TrapReceiver
def __init__(self):
# Create SNMP engine with autogenernated engineID and pre-bound
# to socket transport dispatcher
self.snmpEngine = engine.SnmpEngine()
# Transport setup
# UDP over IPv4, first listening interface/port
config.addTransport(
self.snmpEngine,
udp.domainName + (1,),
udp.UdpTransport().openServerMode(('127.0.0.1', 162))
)
# SNMPv1/2c setup
# SecurityName <-> CommunityName mapping
config.addV1System(self.snmpEngine, 'my-area', 'public')
# Callback function for receiving notifications
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
def cbFun(self,snmpEngine, stateReference, contextEngineId, contextName,
varBinds, cbCtx):
for varBind in varBinds:
oid, value = varBind
trap_source = str(oid)
trap_val = int(value)
#TODO: return trap_source, trap_val
def run(self):
# Register SNMP Application at the SNMP engine
ntfrcv.NotificationReceiver(self.snmpEngine, self.cbFun)
self.snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish
# Run I/O dispatcher which would receive queries and send confirmations
try:
self.snmpEngine.transportDispatcher.runDispatcher()
except:
self.snmpEngine.transportDispatcher.closeDispatcher()
raise
你不能从回调函数中“返回”任何东西。因为它的调用者(主循环)对它的返回值不感兴趣
因此,应该使用
cbCtx
或其他一些全局对象(例如dict
)将回调函数中接收到的信息传递给应用程序的其他部分。cbCtx
对象最初可以传递给NotificationReceiver
,然后它出现在回调函数中例如,您可以让一个线程中的通知接收者将接收到的数据推入
cbCtx
数据结构(例如,它可以是Queue
),然后另一个线程从该Queue
弹出项目并处理它们或者可以在回调函数内部处理接收到的数据。确保它是非阻塞的
相关问题 更多 >
编程相关推荐