簡體   English   中英

我不知道如何解決以下錯誤; RuntimeError:線程“Thread-1”和“Thread-2”中沒有當前事件循環

[英]I don't know how to fix the following error; RuntimeError: There is no current event loop in thread 'Thread-1' and 'Thread-2'

我是編碼的初學者,這是我第一次使用線程。 Threads 是我能為我的項目找到的唯一解決方案。 在項目中,我應該在應用程序上顯示哪個傳感器正在振動,為此我畫了 4 個圓圈來代表傳感器。 所以傳感器 1 將是 bytearray(b'\x03'),傳感器 2 將是 bytearray(b'\x04') 等等。 我想要的是當特征值為 bytearray(b'\x03') 時傳感器 1 的顏色發生變化。

目前使用 python 3.9 創建一個應用程序,該應用程序通過藍牙與 arduino nano 33 iot 連接,我希望能夠每 3 秒讀取一次特性,並根據它應該改變 ZFCC790C72A86190DEB 繪圖顏色的值。 我的目的是讓 while 循環在后台運行,每 3 秒讀取一次特征值。 在我的主屏幕上,基於讀取的值,例如,如果它讀取 bytearray(b'\x03') 它應該改變屏幕上一個繪圖的顏色。 (這就是 if 語句的原因,因此更改顏色的條件將替換 'print("changed color"))。 還會有多個傳感器通過 bytearray(b'\x10') 來檢查 bytearray(b'\x03'),所以我不知道 if 語句是否最好使用,所以如果您有更好的建議,請告訴我知道。

def background():
    async def run(address):
        async with BleakClient(address, loop=loop) as client:
            await client.get_services()
            while True:
                value = await client.read_gatt_char(r_characteristic)
                if await client.read_gatt_char(r_characteristic):
                    time.sleep(.3)
                    print("Read Value: {0}".format(value))

    loop = asyncio.get_event_loop()

def foreground():
    async def run(address):
        async with BleakClient(address, loop=loop) as client:
            await client.get_services()
            value = await client.read_gatt_char(r_characteristic)
            if await client.read_gatt_char(r_characteristic) == bytearray(b'\x03'):
                print("changed color")

    loop = asyncio.get_event_loop()
    asyncio.ensure_future(run(address))
    loop.run_forever()


b = threading.Thread(target=background)
f = threading.Thread(target=foreground)

b.start()
f.start()

但是,當我運行它時,它會向我發送一個錯誤,如下所示;

raise RuntimeError('There is no current event loop in thread %r.'
     raise RuntimeError('There is no current event loop in thread %r.'    raise RuntimeError('There is no current event loop in thread %r.'
 RuntimeError: There is no current event loop in thread 'Thread-1'.
 RuntimeError: There is no current event loop in thread 'Thread-2'.

任何幫助將不勝感激!

嘗試在代碼末尾添加這兩行:

b.join()
f.join()

可能有效,也可能無效,但正如 Tim Roberts 正確所說,將線程和異步結合起來是相當不尋常的,您可能需要重構代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM