【问题标题】:RuntimeWarning: coroutine 'tryit' was never awaitedRuntimeWarning:从未等待协程“tryit”
【发布时间】:2021-10-28 00:15:18
【问题描述】:

我正在编写一个快速例程来检查我的 SamsungTV 的状态(开/关/待机)。电视关闭时它似乎在大约 60 秒后超时,但它在打开或待机时非常快。所以我试图在 10 秒后超时。我遇到了一个错误,正在努力找出等待:

sys.path.append('../')

async def tryit():
    # Normal constructor
    tv = SamsungTVWS('192.168.1.209')

    # Autosave token to file
    token_file = os.path.dirname(os.path.realpath(__file__)) + '/tv-token.txt'
    tv = SamsungTVWS(host='192.168.1.209', port=8002, token_file=token_file)
    # Get device info (device name, model, supported features..)
    try:
        with async_timeout(10):
            info = await tv.rest_device_info()
            tvState = info['device']['PowerState']
    except asyncio.TimeoutError as err:
        tvState = 'off'

    print(tvState)
    return tvState


tryit()

我收到以下错误:我在哪里出错了?

/usr/local/bin/python3.8 /Users/ryanbuckner/PycharmProjects/samsungtvw/tv.py
/Users/ryanbuckner/PycharmProjects/samsungtvw/tv.py:37: RuntimeWarning: coroutine 'tryit' was never awaited
  tryit()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

【问题讨论】:

    标签: python-3.x async-await


    【解决方案1】:

    async 函数需要“等待”,否则它们永远不会运行。如果您运行 tryit(),它将改为返回一个“协程”对象,该对象仅在“等待”后才运行您的代码,或者在您使用 await tv.rest_device_info() 完成的“等待”语句中(当处于异步状态时)函数),或者使用像asyncio.run这样的函数(在函数之外)。

    看起来您在代码的顶层运行tryit()(而不是在另一个函数中),所以我建议使用 asyncio.run。 放:

    import asyncio
    

    在代码的顶部,然后将 tryit() 行替换为:

    asyncio.run(tryit())
    

    这将正确运行您的函数,并使错误消失。

    【讨论】:

    • 非常感谢。我认为这行得通,我只是有一个新错误要通过 info = await tv.rest_device_info() TypeError: object dict can't be used in 'await' expression
    • 这意味着 tv.rest_device_info() 是一个普通函数,而不是一个异步函数(因为它立即返回字典而不是协程) - 换句话说,你不需要等待它,只是正常调用它。 info = tv.rest_device_info()
    猜你喜欢
    • 2018-10-26
    • 2021-10-22
    • 2019-12-15
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 2020-10-10
    • 2022-01-20
    相关资源
    最近更新 更多