Zabbix报错时重新执行Python脚本
Re-execute Python script when error 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
。
因为你运行这是一个循环,如果你碰巧遇到错误,你可以continue
重新启动循环。替换
sender.send(packet)
和
try:
sender.send(packet)
except:
print('Network error. Will retry...')
time.sleep(1)
GPIO.cleanup()
continue # Restart loop
您好,我有以下 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
。
因为你运行这是一个循环,如果你碰巧遇到错误,你可以continue
重新启动循环。替换
sender.send(packet)
和
try:
sender.send(packet)
except:
print('Network error. Will retry...')
time.sleep(1)
GPIO.cleanup()
continue # Restart loop