猿问

为什么python脚本在Pi Zero上随机死亡?

编辑:为了清楚起见:问题不在于MQTT,而在于Pi Zero上的python脚本刚刚死亡。经过一段时间后,脚本将停止存在,并且


sudo ps -ax | grep python 

不再列出运行脚本的进程。


原始问题:


我写了一个简单的脚本,从pi zero读取DHT22传感器,并每分钟将温度和湿度发布到单独的MQTT主题上。在某些时候,脚本只是停止,因为它不会读取或发布更多的读数,即使它在一段时间内运行 True 循环。在我的经纪人中,pi然后显示为“离线”,因为这是最后一个 will 消息。日志文件不包含任何有用的信息,从某种意义上说,只要写入日志文件,脚本就会按预期工作,然后突然出现空白。


def on_connect(client, userdata, flags, rc):

    message = "connected with rc: " + str(rc)

    print(message)

    log(message, mqtt_log_file)

    mqttPub.publish(topicStatusBedroom, "Online", 1, True)

def on_publish(client, obj, mid):

    message = "published with mid: " + str(mid)

    print(message)

    log(message, mqtt_log_file)

def on_disconnect(client, userdata, rc):

    print("client disconnected ok")

    log("client disconnected\n", mqtt_log_file)

    while True:

        try:

            mqttPub.connect(url_str, url_port)

            break # break the while loop, if reconnect works

        except:

            time.sleep(2) # otherwise sleep and retry

def log(message, file):

    file = open(file, "a")

    file.write(message)

    file.close()  

mqttPub = mqtt.Client()

mqttPub.on_connect = on_connect

mqttPub.on_publish = on_publish

mqttPub.on_disconnect = on_disconnect

mqttPub.username_pw_set(username, givenPassword)

mqttPub.will_set(topicStatusBedroom, 'Offline', 1, True)

mqttPub.connect(url_str, url_port)

mqttPub.loop_start() # loop_start handles reconnects automatically


if __name__ == "__main__":

    pin = 22

    sensor = Adafruit_DHT.DHT22

    log_file = 'dht_22_logging.txt'



达令说
浏览 134回答 1
1回答

茅侃侃

答:脚本因 SSH 连接而死机。有效的方法是创建脚本的服务并使用systemd启动它。我确实按照本教程进行了操作:https://learn.sparkfun.com/tutorials/how-to-run-a-raspberry-pi-program-on-startup/all该脚本已经运行了一周,没有任何问题。
随时随地看视频慕课网APP

相关分类

Python
我要回答