从期货到asyncio

时间:2017-08-09 07:58:43

标签: python-3.x python-3.4 python-asyncio

我很困惑让以下内容与asyncio一起工作:

下面的代码片段是查询数字设备(通过snmp)并返回字典,它工作正常,但受multiprocessing.cpu_count()

的限制
def do_polling(netelement, snmp_comm):
    msg = {}
    msg.update({
        'bgp'       : do_lookup_bgp(netelement, snmp_comm),
        'iface'     : do_lookup_iface(netelement, snmp_comm),
        'ifidx'     : do_lookup_ifindex(netelement, snmp_comm),
        'agg'       : do_lookup_agg(netelement, snmp_comm),
    })
    return msg

def save(netelement, job):
    data[netelement] = job.result()

with concurrent.futures.ProcessPoolExecutor(max_workers=multiprocessing.cpu_count()) as executor:
    for k,v in INFO['dev'].items():
        job = executor.submit(do_polling, k, v['snmp_comm'])
        job.add_done_callback(functools.partial(save, k))

所以我想通过改变这样的方式迁移到asyncio方法:

@asyncio.coroutine
def do_polling(netelement, snmp_comm):
    msg = {}
    msg['bgp']      = yield from do_lookup_bgp(netelement, snmp_comm)
    msg['iface']    = yield from do_lookup_iface(netelement, snmp_comm)
    msg['ifidx']    = yield from do_lookup_ifindex(netelement, snmp_comm)
    msg['agg']      = yield from do_lookup_agg(netelement, snmp_comm)

@asyncio.coroutine
def schedule(INFO):
    for k,v in INFO['dev'].items():
        asyncio.async(do_polling(k, v))

asyncio.get_event_loop().run_until_complete(schedule)

但是我收到以下错误:

Traceback (most recent call last):
  File "/home/app/ip-spotlight/code/ixmac.py", line 60, in <module>
    main()
  File "/home/app/ip-spotlight/code/ixmac.py", line 16, in main
    app.ixmac.initialize.run(INFO)
  File "/home/app/ip-spotlight/code/app/ixmac/initialize.py", line 191, in run
    asyncio.get_event_loop().run_until_complete(schedule)
  File "/usr/lib64/python3.4/asyncio/base_events.py", line 353, in run_until_complete
    future = tasks.ensure_future(future, loop=self)
  File "/usr/lib64/python3.4/asyncio/tasks.py", line 553, in ensure_future
    raise TypeError('A Future, a coroutine or an awaitable is required')
TypeError: A Future, a coroutine or an awaitable is required
你能告诉我我做错了吗?

1 个答案:

答案 0 :(得分:3)

您没有将它用作协程。您应该将最后一行更改为:

asyncio.get_event_loop().run_until_complete(schedule(the_info_variable))