首页 > 解决方案 > Python 脚本不会在启动时启动

问题描述

我的 Raspberry Pi 中有一个连接到雨量计的 python 脚本。当雨量计检测到下雨时,脚本显示 0.2 并将其写入文件。这是代码:

#!/usr/bin/env python3
import time
import RPi.GPIO as GPIO
BUTTON_GPIO = 16

if __name__ == '__main__':
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(BUTTON_GPIO, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    pressed = False
    while True:
        # button is pressed when pin is LOW
        if not GPIO.input(BUTTON_GPIO):
            if not pressed:
                print("0.2")
                pressed = True
        # button not pressed (or released)
        else:
            pressed = False
        time.sleep(0.1)

我的想法是使用这样的代码来节省雨水总量。当 python 脚本显示 0.2 > 将其写入文件时。

python3 rain.py >> rain.txt

该代码创建一个文件,但在按 Ctrl + C 完成执行之前不会写入任何内容。

我需要在启动时执行它。我试图将它添加到 crontab 和 rc.local 但不起作用。

我试图用 sudo 和 pi 来执行它。权限为 755。

谢谢!

标签: pythonlinuxraspberry-piraspbianstartup

解决方案


Indeed, this construct command >> file takes the whole of stdout and flushes into the file. It's done only when command execution is over. You must write to the file as soon as your intermediate result is ready:

#!/usr/bin/env python3
import sys
import time
import RPi.GPIO as GPIO
BUTTON_GPIO = 16

if __name__ == '__main__':
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(BUTTON_GPIO, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    pressed = False

    # command line arguments
    if len(sys.argv) > 1: ## file name was passed
        fname = sys.argv[1]
    else: ## standard output
        fname = None

    ## this will clear the file with name `fname`
    ## exchange 'w' for 'a' to keep older data into it
    outfile = open(fname, 'w')
    outfile.close()

    try:
        while True:
            # button is pressed when pin is LOW
            if not GPIO.input(BUTTON_GPIO):
                if not pressed:
                    if fname is None: ## default print
                        print("0.2")
                    else:
                        outfile = open(fname, 'a')
                        print("0.2", file=outfile)
                        outfile.close()
                    pressed = True
            # button not pressed (or released)
            else:
                pressed = False
            time.sleep(0.1)
    except (Exception, KeyboardInterrupt):
        outfile.close()

In this approach you should run python3 rain.py rain.txt and everything will be fine. The try except pattern ensures the file will be properly closed when execution is interrupted by errors or keyboard events.

Notice the file keyword argument in call to print. It selects an open file object to write printed stuff. It defaults to sys.stdout.


推荐阅读