python脚本在启动时手动打印到txt,但不是在启动时通过rc.local在启动时打印到txt

2024-10-05 15:19:13 发布

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

我试图让我的raspberry pi将外部传感器的数据打印到显示器上,同时将其保存到.txt文件中

当通过ssh在shell中启动脚本时,我所做的工作很好。但这会在关闭shell后停止脚本

所以我试着把它放在rc.local文件中,以便在启动时启动它。但这只能起到一半的作用,因为它在显示器上显示数据,但不会将数据保存到文件中

import grovepi

from grovepi import *
from grove_rgb_lcd import *
from time import sleep, strftime
from math import isnan


#port definition
dht_sensor_port = 7 
dht_sensor_type = 0 
led_green = 5
led_red = 6
f = open("hwd.txt", "w")

#rgb display color
setRGB(0,255,0)

while True:
    try:
        [ temp,hum ] = dht(dht_sensor_port,dht_sensor_type)
        print("temp =", temp, "C\thumidity =", hum,"%")
        print("{0},{1}\n".format(strftime("%Y-%m-%d %H:%M:%S"),(temp,hum)), file=f)

        if isnan(temp) is True or isnan(hum) is True:
            raise TypeError('nan error')

        t = str(temp)
        h = str(hum)    
        
        setText_norefresh("Temp:" + t + "C\n" + "Humidity :" + h + "%")

        if hum < 40.0 or hum > 60.0:
            grovepi.digitalWrite(led_red,1)
            grovepi.digitalWrite(led_green,0)
        else:
            grovepi.digitalWrite(led_green,1)
            grovepi.digitalWrite(led_red, 0)

    except (IOError, TypeError) as e:
        print(str(e))
        setText("")

    except KeyboardInterrupt as e:
        print(str(e))
        setText("")
        break

    sleep(1)

``

Tags: 文件数据fromimportledportsensortemp
1条回答
网友
1楼 · 发布于 2024-10-05 15:19:13

您正在运行无限循环,因此需要关闭文件流以将更改保存到文件中。如果在没有循环的情况下运行脚本,您可以看到即使没有关闭steam,更改也会被保存,这是因为它隐式处理。因此,您需要打开和关闭文件流,这可以通过with关键字轻松完成。我认为下面的代码适合您

import grovepi

from grovepi import *
from grove_rgb_lcd import *
from time import sleep, strftime
from math import isnan

# port definition
dht_sensor_port = 7
dht_sensor_type = 0
led_green = 5
led_red = 6

# rgb display color
setRGB(0, 255, 0)

while True:
    try:
        [temp, hum] = dht(dht_sensor_port, dht_sensor_type)
        print("temp =", temp, "C\thumidity =", hum, "%")
        with open("hwd.txt", "w") as f:
            print("{0},{1}\n".format(strftime("%Y-%m-%d %H:%M:%S"), (temp, hum)), file=f)

        if isnan(temp) is True or isnan(hum) is True:
            raise TypeError('nan error')

        t = str(temp)
        h = str(hum)

        setText_norefresh("Temp:" + t + "C\n" + "Humidity :" + h + "%")

        if hum < 40.0 or hum > 60.0:
            grovepi.digitalWrite(led_red, 1)
            grovepi.digitalWrite(led_green, 0)
        else:
            grovepi.digitalWrite(led_green, 1)
            grovepi.digitalWrite(led_red, 0)

    except (IOError, TypeError) as e:
        print(str(e))
        setText("")

    except KeyboardInterrupt as e:
        print(str(e))
        setText("")
        break

    sleep(1)

相关问题 更多 >