我正在尝试编写带有调用可等待对象的方法的类,但不知道如何正确完成。下面的代码可以正常工作,但从下面的警告中可以看出它似乎不正确。
class SmartThings():
async def print_devices(self):
async with aiohttp.ClientSession() as session:
api = pysmartthings.SmartThings(session, TOKEN)
devices = await api.devices()
print(devices[0].name)
def run(self):
asyncio.run(self.print_devices())所以我创建了实例并调用了方法:
x = SmartThings()
x.print_devices()
x.run()..which可以工作(打印所需的输出),但会给我一个RuntimeWarning (可能是在调用x.print_devices()时)
RuntimeWarning: coroutine 'SmartThings.print_devices' was never awaited
x.print_devices()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback发布于 2020-11-29 23:01:47
这几乎是一个一年前的问题,但我以此为起点,我想分享一下结果。如果您正在寻找一个可运行的示例,请参阅以下示例:
import aiohttp
import asyncio
import pysmartthings
# Token: https://account.smartthings.com/tokens
TOKEN = 'e54fde2b-f759-4234-b413-WHATEVER'
def main():
st = SmartThings(TOKEN)
devices = st.print_devices()
for device in devices :
print(device.name)
class SmartThings:
def __init__(self, TOKEN):
self.TOKEN = TOKEN
# return devices
async def search_devices(self):
async with aiohttp.ClientSession() as session:
api = pysmartthings.SmartThings(session, self.TOKEN)
devices = await api.devices()
return devices
def print_devices(self):
loop = asyncio.get_event_loop()
devices = loop.run_until_complete(self.search_devices())
loop.close()
return devices
if __name__ == '__main__':
main()https://stackoverflow.com/questions/59534444
复制相似问题