问题描述
我的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。
谢谢!
解决方法
实际上,此构造command >> file
接受整个stdout
并刷新到文件中。仅在command
执行结束时完成。准备好中间结果后,您必须立即写入文件:
#!/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()
使用这种方法,您应该运行python3 rain.py rain.txt
,一切都会好起来的。 try
except
模式可确保在由于错误或键盘事件而中断执行时正确关闭文件。
在调用file
时注意print
关键字参数。它选择一个打开的文件对象来写入打印内容。默认为sys.stdout
。
尝试
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,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”