简体   繁体   中英

Python script doesn't start on boot

I have a python script in my Raspberry Pi that is connected to a rain gauge. When the rain gauge detects rain, the script shows 0.2 and write it to file. This is the code:

#!/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)

My idea is to use a code like that to save the total amount of rain. When the python script show 0.2 > write it to file.

python3 rain.py >> rain.txt

The code creates a file but doesn't write anything until execution is finished by Ctrl + C.

I need to execute it on boot. I have tried to add it to crontab and rc.local but doesn't work.

I tried to execute it with sudo and pi. The permissions are 755.

Thank you!

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 .

try this

import time
import RPi.GPIO as GPIO
BUTTON_GPIO = 16

if __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)

open a file in append mode with non buffered write. Then when an event occurs, write to that file.

Do not use shell redirect as it will (in this case) buffer all the program output until exit and then write to a file. Of course, the exit never happens as you have a "while True" with no break

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM