bandwith threshold indexer的Python函数:列表索引超出范围E

2024-05-20 00:05:27 发布

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

我目前正试图通过以下教程使我的Raspberry PI 2与Amazon的AWS IoT一起工作:https://www.hackster.io/phantom-formula-e97912/network-monitoring-with-aws-iot-b8b57c?ref=platform&ref_id=425_trending___&offset=12

对于此函数,应发出超过网络带宽阈值的警告:

def monspeed():
    c = checkspeed(-1)
    if c[2] > 2000000: # customize the interface/speed to trigger the warning
        awsmsg = {'state':{ 'reported': {'warning': 'speed' , 'result': c}}}
        payload = json.dumps(awsmsg)
        print (awsmsg)
        client.publish(topic,payload,qos,retain)

我收到以下错误消息:

Traceback (most recent call last): 
File "./netmon.py", line 158, in <module> 
monspeed() 
File "./netmon.py", line 98, in monspeed 
if c[2] > 2000000: # customize the interface/speed to trigger the warning 
IndexError: list index out of range

Tags: thetopyrefifinterfacefilepayload
1条回答
网友
1楼 · 发布于 2024-05-20 00:05:27

该错误表明c对象中的元素少于3个。这取决于checkspeed在接收-1作为参数时的输出。你知道吗

为了查看c发生了什么,请使用try/except块,如下所示:

try:
    if c[2] > 2000000:
        awsmsg = {'state':{ 'reported': {'warning': 'speed' , 'result': c}}}
        payload = json.dumps(awsmsg)
        print (awsmsg)
        client.publish(topic,payload,qos,retain)
except IndexError as e:
    print 'What is "c"?', type(c)
    print 'Values in "c":', c
    raise e

这样做可以在触发错误时检查变量c的类型和值。你知道吗

使用这种策略,您可以看到可能触发错误的变量发生了什么,从而获得有用的信息,找出哪些是错误的。你知道吗

相关问题 更多 >