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。


江户川乱折腾
浏览 124回答 2
2回答

繁华开满天机

尝试这个import timeimport RPi.GPIO as GPIOBUTTON_GPIO = 16if __name__ == '__main__':    outputfile=open("/var/log/rain.txt","a",0)    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:                openputfile.write("0.2\n")                pressed = True        # button not pressed (or released)        else:            pressed = False        time.sleep(0.1)以非缓冲写入的追加模式打开文件。然后当事件发生时,写入该文件。不要使用 shell 重定向,因为它(在这种情况下)会缓冲所有程序输出,直到退出,然后写入文件。当然,退出永远不会发生,因为你有一个没有中断的“while True”

汪汪一只猫

实际上,此构造command >> file将整个stdout并冲入文件。它仅在command执行结束时完成。您必须在中间结果准备就绪后立即写入文件:#!/usr/bin/env python3import sysimport timeimport RPi.GPIO as GPIOBUTTON_GPIO = 16if __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()在这种方法中,你应该运行python3 rain.py rain.txt,一切都会好起来的。该try except模式确保当执行被错误或键盘事件中断时文件将被正确关闭。注意file调用中的关键字参数print。它选择一个打开的文件对象来写入打印的东西。它默认为sys.stdout.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python