【发布时间】:2017-01-05 09:45:46
【问题描述】:
我是这个 python asyncio 主题的新手。我有一个简单的问题: 我有一个包含两个要同时运行的协程的任务。第一个 coroutine(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 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()
这是这个程序的输出:
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
task1: second 5
task1: second 6
task1: second 7
task1: second 8
task1: second 9
task1: second 10
loop is closed
我只想拥有这样的东西:
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
【问题讨论】:
-
为什么不只是
run_until_complete(seq_coroutine)? -
同时执行此操作的想法不仅仅是睡眠和打印。 “my_coroutine”是一个监听其他东西的过程,应该和 seq_coroutine 并行运行,但是为了更容易询问,我只是把它缩短了。
标签: python coroutine python-asyncio