python - 尝试使用 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())
我希望它可以帮助您进一步了解您的程序。
推荐阅读
- php - 使用php从数据库中获取多个json
- apache-superset - 如何为 Apache Superset 添加两个 TIme 列过滤器?
- .net - 为我的 Web 应用程序迁移到 Azure Linux 使内存使用量从 50mb 跃升至 300mb - 这正常吗?
- javascript - 如何在另一个元素中使用 parseFromString 脚本输出
- java - 如何在 android studio 应用程序中翻译单词?
- javascript - 如何在更改屏幕时自动滚动到顶部
- solidity - 类型错误:成员在 unit256 中未找到或可见
- networking - 使用带有完整路径的 fs.unlinkSync 删除项目中的文件,它适用于本地服务器,但在部署到 azure web 应用程序后会出现错误(5xx)
- python - 当我安装 tensorflow 时出现以下错误 ImportError: cannot import name '_set_madvise_hugepage' from 'numpy.core._multiarray_umath'
- php - 如何使用 if 语句检查可用位置?