我试图传递一个字典值给一个函数,我得到这个错误:
Traceback (most recent call last):
File "check_alarm_status.py", line 33, in <module>
main()
File "check_alarm_status.py", line 18, in main
alarmStatus = read_digital_input.main("i1", adams_ips[n])[0]
TypeError: 'NoneType' object is not subscriptable
我已经在其他脚本中使用了相同的函数,但它在循环内的这个脚本中不起作用。下面是我的代码:
import read_digital_input
import change_terminal_light
import time
terminales_ips = { "1":"10.102.12.87", "2":"10.102.12.88", "3":"10.102.12.89", "4":"10.102.12.90", "5":"10.107.12.80"}
adams_ips = {"1":"10.102.12.91", "2":"10.102.12.92", "3":"10.102.12.93", "4":"10.102.12.94", "5":"10.107.12.82"}
previous_state = [0, 0, 0, 0, 0]
state = [False, False, False, False, False]
APAGADO = 0
ENCENDIDO = 5
aux = 0
def main():
while True:
for n in adams_ips:
alarmStatus = read_digital_input.main("i1", adams_ips[n])[0]
state[int(n)-1] = alarmStatus
print("Alarm status ", n, " = ", alarmStatus)
if state[int(n)-1] is not previous_state[int(n)-1]:
print("Terminal ", n, " changed")
if state[int(n)-1] == True:
print("Encendiendo el terminal", n)
change_terminal_light.main(ENCENDIDO, terminales_ips[n])
elif state[int(n)-1] == False:
print("Apagando el terminal", n)
change_terminal_light.main(APAGADO, terminales_ips[n])
previous_state[int(n)-1] = state[int(n)-1]
time.sleep(0.5)
if __name__ == "__main__":
main()
我看到过类似的错误,但我无法解决这个问题。
编辑下面是read_digital_input.py(我像使用其他脚本一样使用它):
import time
from pyModbusTCP.client import ModbusClient
port = "502"
coil_dictionary = {
"i0": 0,
"i1": 1,
"i2": 2,
"i3": 3,
"i4": 4
}
def main(coil, host):
print(host)
try:
c = ModbusClient(host, port)
c.open()
state = c.read_coils(coil_dictionary[coil])
return state
except ValueError:
print("Error with host or port params")
if __name__ == '__main__':
main()
跟踪告诉您这一行有错误
alarmStatus = read_digital_input.main("i1", adams_ips[n])[0]
'NoneType' object is not subscriptable
表示您已经(通过调用[])下标了一个None
对象,因此很可能
read_digital_input.main("i1", adams_ips[n])
呼叫返回None
。也许你需要检查这是否为None,像这样
def main():
while True:
for n in adams_ips:
input = read_digital_input.main("i1", adams_ips[n])
if input is None:
continue
# you may want to do something else than simply skipping here
alarmStatus = alarm[0]
state[int(n)-1] = alarmStatus
print("Alarm status ", n, " = ", alarmStatus)
if state[int(n)-1] is not previous_state[int(n)-1]:
print("Terminal ", n, " changed")
if state[int(n)-1] == True:
print("Encendiendo el terminal", n)
change_terminal_light.main(ENCENDIDO, terminales_ips[n])
elif state[int(n)-1] == False:
print("Apagando el terminal", n)
change_terminal_light.main(APAGADO, terminales_ips[n])
previous_state[int(n)-1] = state[int(n)-1]
time.sleep(0.5)