Python TypeError列表索引必须是整数或片,而不是str

2024-10-08 20:24:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Lambda功能,用于打开/关闭Philip HUE灯泡。我能够执行python脚本&;它在我的本地计算机上运行(无错误)。但是,当我触发Lambda功能(使用IoT按钮)时,我会收到以下错误消息

[ERROR] TypeError: list indices must be integers or slices, not str
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 13, in lambda_handler
    if data["state"]["on"] == False:

有人有什么想法/见解吗?以下是完整的Python脚本:

import requests,json

bridgeIP = "ip_here"
userID = "userID_here"
lightID = "4" #Represents the ID assigned to lightbulb, in the living room.

def lambda_handler(lightID, lambda_context):
    url = f"http://{bridgeIP}/api/{userID}/lights/{lightID}"

    r = requests.get(url)
    data = json.loads(r.text)

    if data["state"]["on"] == False:
        r = requests.put(f"{url}/state", json.dumps({"on":True}))
    elif data["state"]["on"] == True:
        r = requests.put(f"{url}/state", json.dumps({"on":False}))

lambda_handler(lightID, 4)

脚本的最后一行调用lambda_handler()函数。我被告知我不需要这一行,因为我的Lambda在Lambda函数被触发时调用该函数。但是,我(相信)在本地机器上执行脚本时,确实需要手动调用该函数


Tags: lambda函数功能脚本jsonfalseurldata
2条回答

我必须同意@Grismar。捕捉错误:

try:
    if data["state"]["on"] == False:
        r = requests.put(f"{url}/state", json.dumps({"on":True}))
    elif data["state"]["on"] == True:
        r = requests.put(f"{url}/state", json.dumps({"on":False}))
except TypeError:
    dataString = str(Data).strip('[]')
    if dataString["state"]["on"] == False:
        r = requests.put(f"{url}/state", json.dumps({"on":True}))
    elif dataString["state"]["on"] == True:
        r = requests.put(f"{url}/state", json.dumps({"on":False}))

或者您可以先测试data

if isinstance(data,str) == False
    dataString = str(data).strip('[]')
else:
    dataString = data

if dataString["state"]["on"] == False:
    r = requests.put(f"{url}/state", json.dumps({"on":True}))
elif dataString["state"]["on"] == True:
    r = requests.put(f"{url}/state", json.dumps({"on":False}))

dataString变量表示值的字典(而不是列表)。我有必要使用nestedGet()函数来确定“on”键的值

{"on":True} vs {"on":False})

我的全功能python脚本的最终版本可以在here找到

相关问题 更多 >

    热门问题