You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python的pysmartthings库获取SmartThings账户关联的所有位置名称?

解决pysmartthings获取SmartThings位置的问题

第一个错误的原因及修复

第一个代码报错是因为async with语句不能直接写在全局作用域,必须放在async函数内部。你可以把代码包裹进async函数,再用asyncio.run()来执行:

import aiohttp
import pysmartthings
import asyncio

token = 'PERSONAL_ACCESS_TOKEN'

async def main():
    async with aiohttp.ClientSession() as session:
        api = pysmartthings.SmartThings(session, token)
        locations = await api.locations()
        print(len(locations))

        if locations:
            location = locations[0]
            print(location.name)
            print(location.location_id)

asyncio.run(main())

第二个代码无输出的原因及修复

你写的第二个async函数没有被调用,所以程序执行后没有任何输出。另外建议加上token有效性、权限的检查,以及完善异常信息:

import aiohttp
import pysmartthings
import asyncio

token = 'PERSONAL_ACCESS_TOKEN'

async def get_locations():
    try:
        async with aiohttp.ClientSession() as session:
            api = pysmartthings.SmartThings(session, token)
            # 先验证token是否有效
            try:
                await api.refresh_token()
            except Exception as auth_err:
                print(f"Token验证失败: {auth_err}")
                return
            
            locations = await api.locations()
            if not locations:
                print("未找到任何关联位置")
                return
            
            for location in locations:
                print(f"位置名称: {location.name}")
                print(f"位置ID: {location.location_id}")
    except Exception as e:
        print(f"发生错误: {str(e)}")

# 必须调用async函数才会执行
asyncio.run(get_locations())

额外注意事项

  • 确保你的PERSONAL_ACCESS_TOKEN是有效的,并且拥有读取位置的权限(创建token时要勾选对应的权限)
  • 检查网络连接是否正常,能访问SmartThings的API服务
  • 如果还是没有输出,建议打印更详细的异常栈信息,方便排查:
    import traceback
    # 在except块中添加
    traceback.print_exc()
    

内容的提问来源于stack exchange,提问作者EgamerPlayz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 23:02:09