小编par*_*rsa的帖子

Python asyncio:当一个协程完成时停止循环

我在这个python asyncio主题中很新.我有一个简单的问题:我有一个包含两个协同程序的任务可以同时运行.第一个协程(my_coroutine)只会连续打印一些内容,直到达到second_to_sleep.第二个协程(seq_coroutine)将依次调用其他4个协同程序.我的目标是在seq_coroutine完全结束时停止循环.确切地说,我希望my_coroutine在seq_coroutine完成之前保持活着状态.有人可以帮助我吗?

我的代码是这样的:

import asyncio

async def my_coroutine(task,  seconds_to_sleep = 3):
    print("{task_name} started\n".format(task_name=task))
    for i in range(1, seconds_to_sleep):
        await asyncio.sleep(1)
        print("\n{task_name}: second {seconds}\n".format(task_name=task, seconds=i))

async def coroutine1():
    print("coroutine 1 started")
    await asyncio.sleep(1)
    print("coroutine 1 finished\n")


async def coroutine2():
    print("coroutine 2 started")
    await asyncio.sleep(1)
    print("coroutine 2 finished\n")


async def coroutine3():
    print("coroutine 3 started")
    await asyncio.sleep(1)
    print("coroutine 3 finished\n")


async def coroutine4():
    print("coroutine 4 started")
    await asyncio.sleep(1)
    print("coroutine 4 finished\n")


async def seq_coroutine():
    await coroutine1()
    await coroutine2()
    await coroutine3()
    await coroutine4()

def …
Run Code Online (Sandbox Code Playgroud)

python coroutine python-asyncio

1
推荐指数
1
解决办法
2579
查看次数

标签 统计

coroutine ×1

python ×1

python-asyncio ×1