gpt4 book ai didi

python - 如何使用 websocket 库消除此错误?

转载 作者:太空宇宙 更新时间:2023-11-03 20:39:48 24 4
gpt4 key购买 nike

我根据 https://websockets.readthedocs.io/en/stable/intro.html#python-lt-36 中的示例拼凑了以下代码这在 Python 3.6+ 中无疑会更简单,但不幸的是我使用的发行版 (Raspbian) 托管 Python 3.5.3。显然,我做错了什么,但我不知道是什么。我做错了什么,有更简单的方法吗?

def my_callback1(channel):  # Down Arrow Pressed
Return, Cursor = update.upArrow()
if Return:
message = "Control, " + str(Cursor)
asyncio.get_event_loop().run_until_complete(SendMessage(message))

@asyncio.coroutine
def SendMessage(message):
websocket = yield from websockets.connect('ws://localhost:8000')
try:
yield from websocket.send(message)
finally:
yield from websocket.close()

GPIO.add_event_detect(pinsarrow[0], GPIO.RISING, callback=my_callback1, bouncetime=bTime) # Down Arrow
Traceback (most recent call last):
File "/usr/local/sbin/button.py", line 25, in my_callback1
asyncio.get_event_loop().run_until_complete(SendMessage(message))
File "/usr/lib/python3.5/asyncio/events.py", line 671, in get_event_loop
return get_event_loop_policy().get_event_loop()
File "/usr/lib/python3.5/asyncio/events.py", line 583, in get_event_loop
% threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'Dummy-1'.

最佳答案

这是完整的解决方案,感谢 shmee:

def my_callback1(channel):  # Down Arrow Pressed
Return, Cursor = update.downArrow()
if Return:
message = "Control, " + str(Cursor)
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(SendMessage(message))
@asyncio.coroutine
def SendMessage(message):
websocket = yield from websockets.connect('ws://localhost:8000')
try:
yield from websocket.send(message)
finally:
yield from websocket.close()

GPIO.add_event_detect(pinsarrow[0], GPIO.RISING, callback=my_callback1, bouncetime=bTime) # Down Arrow

关于python - 如何使用 websocket 库消除此错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56930440/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com