在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!'
解决方法:
您正在寻找asyncio.ensure_future
(如果您的trollius / asyncio版本太旧而无法确保确保_future,则为asyncio.async):
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!
标签:python-asyncio,python 来源: https://codeday.me/bug/20191119/2039565.html