python 协程 asyncio_Python asyncio:当一个协程是don时停止循环

对于python异步主题,我还是个新手。我有一个简单的问题:

我有一个包含两个协同程序的任务要同时运行。第一个协同程序(my_-co-routine)只会连续打印一些内容,直到达到第二个“从”到“第二个”睡眠。第二个协同程序(seq_-coroutine)将依次调用4个其他协同程序。我的目标是在seq氶co routine结束时停止循环,只要它完全完成。确切地说,我希望我的协同程序在seq\u协同程序完成之前是有效的。有人能帮我吗?在

我的代码是这样的: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 main():

main_loop = asyncio.get_event_loop()

task = [asyncio.ensure_future(my_coroutine("task1", 11)),

asyncio.ensure_future(seq_coroutine())]

try:

print('loop is started\n')

main_loop.run_until_complete(asyncio.gather(*task))

finally:

print('loop is closed')

main_loop.close()

if __name__ == "__main__":

main()

这是该程序的输出:

^{pr2}$

我只想要这样的东西:loop is started

task1 started

coroutine 1 started

task1: second 1

coroutine 1 finished

coroutine 2 started

task1: second 2

coroutine 2 finished

coroutine 3 started

task1: second 3

coroutine 3 finished

coroutine 4 started

task1: second 4

coroutine 4 finished

loop is closed

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值