我尝试创建一个具有队列的多工异步协程,以使用PySNMP收集信息。仅Python 3.5可用。试图基于Python 3.7中的脚本创建我的脚本,但由于异步基本与Python 3.5中的不同,我对此有所保留。
我收到错误消息'asyncio',没有属性'create_task'。
任何人都可以看一下,需要进行哪些更改才能使此脚本正常工作。
import asyncio, random, time
from pysnmp.hlapi.asyncio import *
async def worker(queue):
snmp_engine= SnmpEngine()
while True:
next_ip = await queue.get()
errorIndication, errorStatus, errorIndex, varBinds = await getCmd(SnmpEngine(), CommunityData('public'),
UdpTransportTarget((next_ip, 161)), ContextData(), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))
)
print(errorIndication, errorStatus, errorIndex, varBinds)
queue.task_done()
async def main():
queue = asyncio.Queue()
for _ in range(100):
queue.put_nowait("104.236.166.95")
tasks = []
for i in range(3):
task = asyncio.create_task(worker( queue))
tasks.append(task)
started_at = time.monotonic()
await queue.join()
total_slept_for = time.monotonic() - started_at
for task in tasks:
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
print(total_slept_for)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
在Python 3.7之前,可以使用asyncio.ensure_future()
函数代替asyncio.create_task()
。