相关疑难解决方法(0)

Python 3.5中的协同程序和未来/任务之间的区别?

假设我们有一个虚函数:

async def foo(arg):
    result = await some_remote_call(arg)
    return result.upper()
Run Code Online (Sandbox Code Playgroud)

有什么区别:

coros = []
for i in range(5):
    coros.append(foo(i))

loop = get_event_loop()
loop.run_until_complete(wait(coros))
Run Code Online (Sandbox Code Playgroud)

和:

from asyncio import ensure_future

futures = []
for i in range(5):
    futures.append(ensure_future(foo(i)))

loop = get_event_loop()
loop.run_until_complete(wait(futures))
Run Code Online (Sandbox Code Playgroud)

注意:该示例返回结果,但这不是问题的焦点.当返回值很重要时,请使用gather()而不是wait().

无论回报价值如何,我都在寻求清晰度ensure_future().wait(coros)并且wait(futures)都运行协同程序,所以何时以及为什么要将协程包装进去ensure_future

基本上,使用Python 3.5运行一堆非阻塞操作的正确方法(tm)是async什么?

如果我想批量通话,如果需要额外的积分?例如,我需要调用some_remote_call(...)1000次,但我不想粉碎Web服务器/数据库/等1000个同时连接.这对于线程或进程池是可行的,但有没有办法做到这一点asyncio

python python-asyncio python-3.5

93
推荐指数
4
解决办法
2万
查看次数

python asyncio add_done_callback with async def

我有两个函数:第一个def_a是异步函数,第二个是def_b常规函数,调用结果def_a作为add_done_callback函数的回调函数.

我的代码看起来像这样:

import asyncio

def def_b(result):
    next_number = result.result()
    # some work on the next_number
    print(next_number + 1)

async def def_a(number):
    await some_async_work(number)
    return number + 1

loop = asyncio.get_event_loop()
task = asyncio.ensure_future(def_a(1))
task.add_done_callback(def_b)
response = loop.run_until_complete(task)
loop.close()
Run Code Online (Sandbox Code Playgroud)

它的工作非常完美.

当第二个函数def_b变为异步时,问题就开始了.现在它看起来像这样:

async def def_b(result):
    next_number = result.result()
    # some asynchronous work on the next_number
    print(next_number + 1)
Run Code Online (Sandbox Code Playgroud)

但是现在我无法将它提供给add_done_callback函数,因为它不是常规函数.

我的问题是 - 它是否可能,如果是异步的,我怎么能提供def_badd_done_callback函数def_b

python coroutine python-3.x async-await python-asyncio

12
推荐指数
2
解决办法
8053
查看次数