在asyncio中执行fire and forget任务

时间:2015-08-12 22:04:07

标签: python python-asyncio

使用Python的asyncio库时,如何启动任务然后不关心它的完成?

实施例

@asyncio.coroutine
def f():
    yield From(asyncio.sleep(1))
    print("world!")

@asyncio.coroutine
def g():
    desired_operation(f())
    print("Hello, ")
    yield From(asyncio.sleep(2))

>>> loop.run_until_complete(g())
'Hello, world!'

1 个答案:

答案 0 :(得分:3)

您正在寻找asyncio.ensure_future(或asyncio.async如果您的trollius / asyncio版本太旧而无法ensure_future):< / p>

from __future__ import print_function

import trollius as asyncio
from trollius import From

@asyncio.coroutine
def f():
    yield From(asyncio.sleep(1))
    print("world!")

@asyncio.coroutine
def g():
    asyncio.ensure_future(f())
    print("Hello, ", end='')
    yield From(asyncio.sleep(2))

loop = asyncio.get_event_loop()
loop.run_until_complete(g())

输出:

Hello, world!