[英]uasyncio.create_task does not run coroutine (micropython)
在我開始關於 github 的問題之前,我只是想知道,如果我做錯了。 這個基本示例應該開始一個循環,並且在調用stop方法后它應該停止。 但是,根本不執行print("while loop")
。
import uasyncio
import utime
class Test:
def __init__(self):
pass
def run_loop(self):
self.should_run = 1
uasyncio.create_task(self._while_loop())
async def _while_loop(self):
print("while loop") # <--------- gets never called!
counter = 0
while self.should_run == 1:
counter += 1
print(counter)
await uasyncio.sleep_ms(100)
def stop(self):
self.should_run = 0
print("should stop now")
test = Test()
test.run_loop()
print("looop started.. wait..")
utime.sleep(3)
print("...waited..")
test.stop()
在 python腳本中,默認情況下所有執行都是同步的。 要提供異步功能,必須創建一個異步上下文。 這是通過 asyncio.run() 完成的 // 由於 python 的性質,它將等待所有內部異步任務終止。
正如micropython-uasyncio文檔所說,一個典型的異步應用程序被包裝到異步上下文中(例如main函數)。
這就是我解決上述問題的方法:
import uasyncio as asyncio
import utime
class Test:
run = 0
def __init__(self):
pass
def run_loop(self):
self.run = 1
asyncio.create_task(self._while_loop())
async def _while_loop(self):
print("while loop, should_run:", self.run)
counter = 0
while self.run == 1:
counter += 1
print(counter)
await asyncio.sleep_ms(100)
def stop(self):
self.run = 0
print("should stop now")
async def main():
test = Test()
test.run_loop()
print("looop started.. wait..")
await asyncio.sleep(2)
test.stop()
asyncio.run(main())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.