MicroPython uasyncio在micro controller和普通Python上的行为不同:任务只是保持运行

2024-06-01 20:41:57 发布

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

这是我的例子:

try:
    import uasyncio as asyncio
except ImportError:
    import asyncio

async def count():
    i = 0
    while True:
        print(i)
        i += 1
        await asyncio.sleep(1)

async def main():
    asyncio.create_task(count())
    await asyncio.sleep(5)

asyncio.run(main())
asyncio.run(main())

在常规Python中,我得到:

0
1
2
3
4
0
1
2
3
4

但是,MicroPython会产生以下输出:

0
1
2
3
4
0
5
1
6
2
7
3
8
4
9

因此,第一个任务不会停止,而是在第二个任务的运行时保持运行


Tags: runimportasyncioasyncmaindefascount
2条回答

显然,这是目前预期的行为:

By default uasyncio retains state, as discussed here. Arguably in the interests of CPython compatibility it shouldn't, but on occasion this behaviour can be useful. Currently the user has the choice of whether to allow retained state.

资料来源:https://github.com/micropython/micropython/issues/7471

因此,一种解决方法是在asyncio.run的后续调用之间调用asyncio.new_event_loop

try:
    import uasyncio as asyncio
except ImportError:
    import asyncio

async def count():
    i = 0
    while True:
        print(i)
        i += 1
        await asyncio.sleep(1)

async def main():
    asyncio.create_task(count())
    await asyncio.sleep(5)

asyncio.run(main())
asyncio.new_event_loop()
asyncio.run(main())

我相信这是一个缺陷,我已经记录了问题#7471来跟踪它(还有一个解决方法)。感谢您以清晰、可复制的示例报告问题

相关问题 更多 >