[英]Trying to make an async function that runs forever using run_forever
我正在嘗試訪問 websocket 來監聽一些信息,所以我想使用 run_forever 命令繼續監聽直到我停止程序,但是當我收到下面的錯誤時,有人能告訴我我做錯了什么嗎?
代碼:
loop = asyncio.get_event_loop()
async def listen():
url = "websocket url starting with wss"
async with websockets.connect(url) as ws:
msg = await ws.recv()
print(msg)
loop.run_forever(listen())
然后錯誤說:
RuntimeWarning: coroutine 'listen' was never awaited
loop.run_forever(listen())
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):
File "C:\Users\...", line 18, in <module>
loop.run_forever(listen())
TypeError: run_forever() takes 1 positional argument but 2 were given
我嘗試將您的腳本加載到 Python 3.9.6 中,但我看到了您的錯誤。
這是我運行它的方式(您需要輸入正確的 URL):
import asyncio, websockets
async def listen():
url = "websocket url starting with wss"
async with websockets.connect(url) as ws:
msg = await ws.recv()
print(msg)
async def main():
loop = asyncio.get_event_loop()
loop.run_forever(await listen())
if __name__ == "__main__":
asyncio.run(main())
我希望它可以幫助您進一步了解您的程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.