【发布时间】:2022-11-11 01:20:20
【问题描述】:
我正在使用 websockets 和 asyncio 来管理我的应用程序中的连接。
发送方法是异步的
async def send(self, message):
logging.debug('send {}'.format(message))
await self.websocket.send(message)
我通常在异步线程中使用它,一切都很好。 只有一种情况我需要从同步方法中调用它。
我试过这样称呼它
asyncio.run(ws.send(json.dumps(payload)))
但我得到了这个例外
Task <Task pending name='Task-134' coro=<WebSocketCommonProtocol.send() running at /usr/local/lib/python3.8/dist-packages/websockets/legacy/protocol.py:631> cb=[_run_until_complete_cb() at /usr/lib/python3.8/asyncio/base_events.py:184]> got Future <Future pending> attached to a different loop
所以我尝试使用当前循环
loop = asyncio.get_event_loop()
asyncio.run(ws.send(json.dumps(payload)), loop=loop)
但
There is no current event loop in thread 'Thread-37'.
可以做什么?
【问题讨论】:
-
您的脚本是否混合了
asyncio和threading?使用asyncio.to_thread将线程放在asyncio一侧可能会更好 -
主要问题是
self.websocket...将绑定到与您尝试同步调用的单独线程中的循环不同的循环。
标签: python python-3.x python-asyncio