错误Zabbix时重新执行Python脚本

时间:2018-04-02 13:54:07

标签: python raspberry-pi3 zabbix

您好我有以下Python脚本raspi.py

import RPi.GPIO as GPIO
import time
from pyzabbix import ZabbixSender, ZabbixMetric
#GPIO.setmode(GPIO.BCM)
#GPIO.setup(22,GPIO.IN)
while 1:
      GPIO.setmode(GPIO.BCM)
      GPIO.setup(22,GPIO.IN)
      value = GPIO.input(22)
      if GPIO.input(22):
          packet = [
              ZabbixMetric('raspi','acloss',value),
          ]
          sender = ZabbixSender(use_config=True)
          sender.send(packet)
          print ("AC OK",GPIO.input(22))
          GPIO.cleanup()
          time.sleep(5)
      else:
          packet = [
              ZabbixMetric('raspi','acloss',value),
          ]
          sender = ZabbixSender(use_config=True)
          sender.send(packet)
          print ("AC LOSS",GPIO.input(22))
          GPIO.cleanup()
          time.sleep(5)

      time.sleep(1)

问题是当没有与zabbix连接时,例如没有互联网,然后程序退出并出现错误:

Traceback (most recent call last):
File "./raspifinal.py", line 26, in <module>
sender.send(packet)
File "/home/pyzabbix/sender.py", line 383, in send
result.parse(self._chunk_send(metrics[m:m + self.chunk_size]))
File "/home/pyzabbix/sender.py", line 352, in _chunk_send
connection.connect(host_addr)
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 101] Network is unreachable

我需要一个Python或Bash脚本,当它出来时重新执行rapsi.py

1 个答案:

答案 0 :(得分:0)

由于你在循环中运行它,如果你发生了错误,你可以continue重新启动循环。取代

      sender.send(packet)

      try:
          sender.send(packet) 
      except:
          print('Network error. Will retry...')
          time.sleep(1)
          GPIO.cleanup()
          continue  # Restart loop