Python脚本由于未知原因随机崩溃

2024-10-03 06:27:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用以下脚本作为一个自制的能源监测系统的基础。该脚本充当连接到串行端口的基于arduino的接收器之间的网关,并通过MQTT和httppost传递它。脚本打算无限期运行。然而,它会以随机间隔崩溃,从一小时到一周不等。我不明白为什么。任何关于如何确定错误原因以及如何记录错误的指示都将不胜感激。以下是脚本:

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)

谢谢你!你知道吗

猴面包树


Tags: import脚本datatimedeviceserialpublishtemp
1条回答
网友
1楼 · 发布于 2024-10-03 06:27:52

第二个try语句捕获以下异常:

except serial.serialutil.SerialException:

但是如果代码块生成不同的异常呢?脚本将退出。添加第二个except,如第一个try循环,以捕获任何其他异常,并将它们打印到日志中。你知道吗

相关问题 更多 >