运行时警告:从未等待协程"tryit"



我正在编写一个快速的例程来检查我的三星电视的状态(打开/关闭/待机)。当电视关闭时,它似乎会在大约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()

我得到以下错误:Where did I go wrong here?

/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

async函数需要"等待",否则它们永远不会运行。如果你运行tryit(),它将返回一个"协程"对象,只会运行你的代码,一旦它是'等待',要么在'等待'语句,就像你已经做了与await tv.rest_device_info()(当在一个异步函数),或使用一个函数像asyncio.run(当在一个函数外)。

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

import asyncio

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

asyncio.run(tryit())

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

最新更新