Search code examples
pythonraspberry-pi3zabbix

Re-execute Python script when error Zabbix


Hello I have the following Python script 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)

The problem is when not connection with the zabbix, e.g. no Internet, then the program exits with an error:

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

I need a Python or Bash script that re-executes rapsi.py when it gets out.


Solution

  • Since you're running this on a loop, you can just continue to restart the loop if you happen uppon the error. Replace

          sender.send(packet)
    

    with

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