首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我不知道如何修复以下错误;RuntimeError:线程' thread -1‘和'Thread-2’中没有当前事件循环

我不知道如何修复以下错误;RuntimeError:线程' thread -1‘和'Thread-2’中没有当前事件循环
EN

Stack Overflow用户
提问于 2021-04-06 09:18:59
回答 1查看 48关注 0票数 0

我是一个编程的初学者,这是我第一次使用线程。线程是我能为我的项目找到的唯一解决方案。在项目中,我应该在应用程序上显示哪个传感器正在振动,为此,我画了4个圆圈来表示传感器。因此,传感器1将是bytearray(b'\x03'),传感器2将是bytearray(b'\x04'),依此类推。我想要的是当特征值为bytearray(b'\x03')时,传感器1的颜色发生变化。

目前正在使用Python3.9创建一个应用程序,它通过蓝牙与arduino nano 33物联网连接,我希望能够每秒读取.3的特征,并根据它应该改变画布绘画的颜色的值。我在这里的目的是让while循环在后台运行,每隔.3秒读取特征值。在我的主屏幕上,根据读取的值,例如,如果它读取bytearray(b'\x03'),它应该改变屏幕上一幅画的颜色。(这就是为什么使用if语句,以便更改颜色的条件将替换‘print(“更改颜色”))。此外,将有多个传感器来检查bytearray(b'\x03')到bytearray(b'\x10'),所以我不知道if语句是否最好使用,所以如果您有更好的建议,请让我知道。

代码语言:javascript
复制
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()

然而,当我运行它时,它向我返回一个错误,如下所示;

代码语言:javascript
复制
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'.

任何帮助都将不胜感激!

EN

回答 1

Stack Overflow用户

发布于 2021-04-06 17:40:29

尝试在代码的末尾添加以下两行:

代码语言:javascript
复制
b.join()
f.join()

可能会工作,也可能不会工作,但正如Tim Roberts所说的那样,组合线程和异步是相当不寻常的,您可能需要重构您的代码。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66961593

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档