【问题标题】:How to stop "loop.run_forever()" with "loop.stop()" in Python?如何在 Python 中用 \"loop.stop()\" 停止 \"loop.run_forever()\"?
【发布时间】:2022-11-09 21:23:39
【问题描述】:

我试图在 Python 中用loop.stop() 停止loop.run_forever(),如下所示:

import asyncio

async def test():
    for _ in range(3):
        print("Test")

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

loop.create_task(test())

loop.run_forever()
loop.stop() # Here

文档在下面提到了loop.run_forever(),但loop.stop() 并没有停止loop.run_forever()

运行事件循环,直到调用 stop()。

那么,如何在 Python 中用loop.stop() 停止loop.run_forever()

【问题讨论】:

    标签: python python-3.x asynchronous python-asyncio event-loop


    【解决方案1】:

    你需要打电话loop.stop()test()通过传递loop测试()`如下所示:

    import asyncio
    
    async def test(loop):
        for _ in range(3):
            print("Test")
        loop.stop() # Here
    
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
                         
    loop.create_task(test(loop)) # Pass "loop" to "test()"
    
    loop.run_forever()
    

    【讨论】:

      猜你喜欢
      • 2021-11-23
      • 2018-03-14
      • 2019-08-05
      • 1970-01-01
      • 2020-05-28
      • 2013-11-19
      • 2013-08-03
      • 2015-10-28
      • 1970-01-01
      相关资源
      最近更新 更多