如何在Python 3.5中创建带有队列的多工作者协程

问题描述 投票:0回答:1

我正在尝试创建一个具有队列的多工异步协程,以使用PySNMP收集信息。仅Python 3.5可用。我试图基于Python 3.7中的脚本创建脚本,但由于异步基本原理在Python 3.5中有所不同,因此陷入了这一困境。

我收到错误消息:'asyncio' has no attribute '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.5 python-asyncio pysnmp
1个回答
0
投票

在Python 3.7之前,可以使用asyncio.ensure_future()函数代替asyncio.create_task()

© www.soinside.com 2019 - 2024. All rights reserved.