【问题标题】:Manage asyncio coroutines in dict在 dict 中管理异步协程
【发布时间】:2020-01-21 13:41:06
【问题描述】:

我想在 dict 中管理一些协程,同时运行一个主协程。 具体来说,我想启动无尽的协程,将它们的处理程序放在 dict 中,然后再次通过 dict 调用取消它们。在我的示例中,我想启动 4 个协程,它们将使用协程 doomsday 再次取消。我正在使用 Python 3.6。

import asyncio
import traceback


async def add_to_handler(node, func):
    func_handler[node] = asyncio.ensure_future(func, loop=loop)
    return

async def test_func1():
    while True:
        print("1 - HeNlO")
        await asyncio.sleep(1)

async def test_func2():
    while True:
        print("2 - TestFunc2")
        await asyncio.sleep(2)


async def test_func3():
    while True:
        print("3 - Tukan")
        await asyncio.sleep(3)


async def test_func4():
    while True:
        print("4 - Do Coro!")
        await asyncio.sleep(4)


async def doomsday():
    # Cancel coroutine every 10 seconds
    print("launch doomsday")
    for i in range(len(func_handler)):
        await asyncio.sleep(10)
        print("start cancelling with {}".format(i))
        func_handler[str(i + 1)].cancel()
    return

async def main():
    await add_to_handler("1", test_func1)
    await add_to_handler("2", test_func2)
    await add_to_handler("3", test_func3)
    await add_to_handler("4", test_func4)
    await doomsday()
    while True:
        print("z..z..Z..Z...Z")
        print(func_handler)
        await asyncio.sleep(5)

func_handler = {}

loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(main())
except KeyboardInterrupt:
    print("stop loop")
    loop.close()

我尝试使用 AbstractEventLoop 的 .call_latermethod 而不是无休止的 while 循环,但它仍然不想工作,而且似乎我的协程被视为函数,但我不知道为什么。我的错在哪里?

【问题讨论】:

    标签: python python-3.x python-3.6 python-asyncio coroutine


    【解决方案1】:

    尝试更改此功能:

    async def add_to_handler(node, func):
        func_handler[node] = asyncio.ensure_future(func(), loop=loop)
        return None
    

    注意 asyncio.ensure_future(func(),loop=loop)

    【讨论】:

    • 有时缺少一些小东西,谢谢。我尝试将 while True 循环和 asyncio.ensure_future(main_sleep(),loop=loop) 一起放在协程中的 main 中(要清楚,它没有在字典中列出)。但是在取消 dict 中的最后一个协程后,循环会自行退出(以明确的方式),但我的 main_sleep() 协程不应该仍然挂起/运行吗?
    • 如果loop.run_until_complete(main()) 将完成执行并且asyncio.ensure_future(main_sleep(), loop=loop) 在异步循环中执行它不会阻止您的主函数完成其执行,则例程 main_sleep() 将自动终止,您可以在现在的方式或只是将其称为await main_sleep()
    猜你喜欢
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-26
    • 1970-01-01
    • 2015-05-07
    相关资源
    最近更新 更多