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

python script printing to txt when startet manually but not at startup via rc.local on bootup

我正在尝试让我的 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)

``

您正在 运行 进行无限循环,因此您需要关闭文件流以将更改保存到您的文件中。如果你 运行 你的脚本没有循环,你可以看到即使没有关闭 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)