Python 脚本因未知原因随机崩溃
Python script crashes randomly for unknown reason
我正在使用以下脚本作为自制能源监控系统的基础。该脚本用作连接到串行端口的基于 arduino 的接收器之间的网关,并通过 MQTT 和 http POST 传递它。该脚本旨在无限期 运行。然而,它会随机崩溃,从一小时到一周不等。我不知道为什么。任何关于如何确定为什么以及如何记录错误的指示将不胜感激。这是脚本:
import time
import datetime
import requests
import paho.mqtt.publish as publish
#import csv
import logging
logging.basicConfig(level=logging.ERROR, filename='serial-read.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')
device = '/dev/ttyUSB0' #this will have to be changed to the serial port you are using
data = ""
pieces = ""
while True:
while True:
try:
receiver = serial.Serial(device, 57600)
receiver.flushInput()
except serial.SerialException:
print "cannot connect. will try again..."
time.sleep(10)
else:
break
try:
data = receiver.readline()
#print (data)
#print repr(data)
#with open ("data_log.csv","a") as f:
#writer = csv.writer(f,delimiter=",")
#writer.writerow([time.time(),data])
pieces = data.split(" ")
try:
nodeid = int(pieces[0])
except ValueError:
pass
try:
data1 = int(pieces[1])
data2 = int(pieces[2])
data3 = int(pieces[3])
data4 = int(pieces[4])
except IndexError:
pass
#print nodeid
if nodeid == 6:
#print "Power:"
Irms = data3 + data4
print Irms
localtime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
localtime = "'" + localtime + "'"
#print localtime
payload = {"timestamp" : localtime, "Irms" : Irms}
r = requests.post('http://www.********.ca/*****.php', params=payload)
#print(r.url)
publish.single("myHome/energy/power", Irms, hostname="192.168.1.120")
elif nodeid == 2:
temp = float(data1)/10
#print "temp:"
#print temp
hum = data3
publish.single("myHome/garage/temperature", temp, hostname="192.168.1.120")
publish.single("myHome/garage/humidity", hum, hostname="192.168.1.120")
temphum = str(temp) + " " + str(hum)
publish.single("myHome/garage/temphum", temphum, hostname="192.168.1.120")
#print temphum
except serial.serialutil.SerialException:
print "no device connected. Please reconnect device..."
receiver.close()
time.sleep(5)
谢谢!
猴面包树
您的第二个 try
语句捕获以下异常:
except serial.serialutil.SerialException:
但是如果代码块生成不同的异常怎么办?脚本将退出。添加第二个 except
,就像在第一个 try
循环中一样,以捕获任何其他异常,并将它们打印到您的日志中。
我正在使用以下脚本作为自制能源监控系统的基础。该脚本用作连接到串行端口的基于 arduino 的接收器之间的网关,并通过 MQTT 和 http POST 传递它。该脚本旨在无限期 运行。然而,它会随机崩溃,从一小时到一周不等。我不知道为什么。任何关于如何确定为什么以及如何记录错误的指示将不胜感激。这是脚本:
import time
import datetime
import requests
import paho.mqtt.publish as publish
#import csv
import logging
logging.basicConfig(level=logging.ERROR, filename='serial-read.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')
device = '/dev/ttyUSB0' #this will have to be changed to the serial port you are using
data = ""
pieces = ""
while True:
while True:
try:
receiver = serial.Serial(device, 57600)
receiver.flushInput()
except serial.SerialException:
print "cannot connect. will try again..."
time.sleep(10)
else:
break
try:
data = receiver.readline()
#print (data)
#print repr(data)
#with open ("data_log.csv","a") as f:
#writer = csv.writer(f,delimiter=",")
#writer.writerow([time.time(),data])
pieces = data.split(" ")
try:
nodeid = int(pieces[0])
except ValueError:
pass
try:
data1 = int(pieces[1])
data2 = int(pieces[2])
data3 = int(pieces[3])
data4 = int(pieces[4])
except IndexError:
pass
#print nodeid
if nodeid == 6:
#print "Power:"
Irms = data3 + data4
print Irms
localtime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
localtime = "'" + localtime + "'"
#print localtime
payload = {"timestamp" : localtime, "Irms" : Irms}
r = requests.post('http://www.********.ca/*****.php', params=payload)
#print(r.url)
publish.single("myHome/energy/power", Irms, hostname="192.168.1.120")
elif nodeid == 2:
temp = float(data1)/10
#print "temp:"
#print temp
hum = data3
publish.single("myHome/garage/temperature", temp, hostname="192.168.1.120")
publish.single("myHome/garage/humidity", hum, hostname="192.168.1.120")
temphum = str(temp) + " " + str(hum)
publish.single("myHome/garage/temphum", temphum, hostname="192.168.1.120")
#print temphum
except serial.serialutil.SerialException:
print "no device connected. Please reconnect device..."
receiver.close()
time.sleep(5)
谢谢!
猴面包树
您的第二个 try
语句捕获以下异常:
except serial.serialutil.SerialException:
但是如果代码块生成不同的异常怎么办?脚本将退出。添加第二个 except
,就像在第一个 try
循环中一样,以捕获任何其他异常,并将它们打印到您的日志中。