使用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!'
答案 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!