【发布时间】:2020-04-04 10:18:13
【问题描述】:
我尝试创建一个类似于 asyncio.gather 的方法,但它会按顺序而不是异步执行任务列表:
async def in_sequence(*tasks):
"""Executes tasks in sequence"""
for task in tasks:
await task
接下来这个方法应该是这样使用的:
async def some_work(work_name):
"""Do some work"""
print(f"Start {work_name}")
await asyncio.sleep(1)
if raise_exception:
raise RuntimeError(f"{work_name} raise an exception")
print(f"Finish {work_name}")
async def main():
try:
await asyncio.gather(
some_work("work1"), # work1, work2, in_sequence and work5 executed in concurrently
some_work("work2"),
in_sequence(
some_work("work3"), # work3 and work4 executed in sequence
some_work("work4")
),
some_work("work5"),
except RuntimeError as error:
print(error) # raise an exception at any point to terminate
在我尝试在 some_work 中抛出异常之前一切正常:
async def main():
try:
await asyncio.gather(
some_work("work1"),
some_work("work2"),
in_sequence(
some_work("work3", raise_exception=True), # raise an exception here
some_work("work4")
),
some_work("work5"),
except RuntimeError as error:
print(error)
紧接着,我收到以下错误消息:
RuntimeWarning: coroutine 'some_work' was never awaited
我阅读了文档并继续实验:
async def in_sequence(*tasks):
"""Executes tasks in sequence"""
_tasks = []
for task in tasks:
_tasks.append(asyncio.create_task(task))
for _task in _tasks:
await _task
这个版本按预期工作!
对此,我有下一个问题:
- 为什么第二个版本有效而第一个无效?
- asyncio 是否已经拥有执行任务列表的工具 顺序?
- 我选择了正确的实现方法还是有更好的实现方法 选项?
【问题讨论】:
标签: python async-await python-asyncio