Python异步函数在while循环内无法执行的问题求助
Python异步函数在while循环内无法执行问题
我是Python新手,碰到个问题:异步函数fetch_depth_snapshot()和process_buffered_messages()放在while循环外时代码正常运行,但移到循环内subscribe_to_streams()之后,这两个函数完全不执行,循环里其他3个函数却能正常跑。
我需要这两个函数在订阅流完成后执行,避免错过WebSocket消息,但试了好几个位置都没用。通过Flask页面没数据、打印日志确认这俩函数根本没被调用,求解决办法。
可正常运行的代码
async def connect_and_listen(self, retry_count=0, max_retries=5, backoff_factor=1): if not self.initialized: await self.fetch_depth_snapshot() await self.process_buffered_messages() while self.running and retry_count < max_retries: try: self.websocket = await websockets.connect(self.uri) await self.stomp_connect() await self.listen_to_messages() await self.subscribe_to_streams() retry_count = 0 # Reset retry count on successful connection except Exception as e: logging.error(f"Connection error: {e}") retry_count += 1 sleep_time = backoff_factor * (2 ** retry_count) logging.info(f"Retrying connection in {sleep_time} seconds.") await asyncio.sleep(sleep_time)
无法运行的代码
async def connect_and_listen(self, retry_count=0, max_retries=5, backoff_factor=1): while self.running and retry_count < max_retries: try: self.websocket = await websockets.connect(self.uri) await self.stomp_connect() await self.listen_to_messages() await self.subscribe_to_streams() retry_count = 0 # Reset retry count on successful connection if not self.initialized: await self.fetch_depth_snapshot() await self.process_buffered_messages() except Exception as e: logging.error(f"Connection error: {e}") retry_count += 1 sleep_time = backoff_factor * (2 ** retry_count) logging.info(f"Retrying connection in {sleep_time} seconds.") await asyncio.sleep(sleep_time)
内容的提问来源于stack exchange,提问作者iSpeakGeek
相关产品推荐
相关产品推荐

