简体   繁体   English

尝试使用 run_forever 创建一个永远运行的异步函数

[英]Trying to make an async function that runs forever using run_forever

I am trying to access a websocket to listen to some information and so I want to use the run_forever command to keep listening until I stop the program, but when I do I get the error below, could someone tell me what I am doing wrong?我正在尝试访问 websocket 来监听一些信息,所以我想使用 run_forever 命令继续监听直到我停止程序,但是当我收到下面的错误时,有人能告诉我我做错了什么吗?

Code:代码:

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())

the error then says:然后错误说:

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

I tried loading your script into Python 3.9.6 and i saw your error.我尝试将您的脚本加载到 Python 3.9.6 中,但我看到了您的错误。

This is how i got it to run (you need to enter the proper URL):这是我运行它的方式(您需要输入正确的 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())

I hope it can help you to get further with your program.我希望它可以帮助您进一步了解您的程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM