在asyncio模块中,如何使用我们想继续使用的变量中断事件循环

2024-04-24 19:46:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python中Asyncio模块的使用还比较陌生。假设有两个函数我想异步运行。函数_A()基本上是在运行循环,需要在特定条件下用“if”语句停止循环。你知道吗

我不确定eventloop究竟是如何工作的,只知道当我运行循环。停止(),它将终止内核并重新启动它,这样在中断eventloop后要保留的“lst”将在终止内核后自动删除。你知道吗

我想做的是:

global lst
lst = []

import asyncio
    async def function_A():        
        for i in range(0,100):
            lst.append(i)
            if len(lst) == 10:
               loop.stop()  #  <== this doesn't work well 

    async def function_B():
       # do something else

loop = asyncio.get_event_loop()
tasks = asyncio.gather(function_A(), function_B())
loop.run_until_complete(tasks)

## break out of the event loop ## 
# lst is saved and continue to another process with "lst"

有没有办法做这样的工作?一个简短的例子是非常感谢。你知道吗


Tags: 模块函数loopeventasyncioasyncifdef
1条回答
网友
1楼 · 发布于 2024-04-24 19:46:46

尝试使用loop.close(),而不是调用loop.stop()。你知道吗

以下操作将停止循环。你知道吗

loop.stop()

Stop the event loop.

关闭也将丢弃所有挂起的任务。你知道吗

loop.close()

Close the event loop.

The loop must not be running when this function is called. Any pending callbacks will be discarded.

This method clears all queues and shuts down the executor, but does not wait for the executor to finish.

This method is idempotent and irreversible. No other methods should be called after the event loop is closed.

或者您可以返回而不是调用上述函数,并等待function_B返回。 只有这样才能关闭循环。你知道吗

相关问题 更多 >