我试图创建一个类似于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是否已经拥有按顺序执行任务列表的工具?
我是否选择了正确的实现方法,或者是否有更好的选择?
慕桂英4014372
当年话下
精慕HU
白板的微信
相关分类