2 回答

TA贡献1816条经验 获得超4个赞
尝试这个
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)
以非缓冲写入的追加模式打开文件。然后当事件发生时,写入该文件。
不要使用 shell 重定向,因为它(在这种情况下)会缓冲所有程序输出,直到退出,然后写入文件。当然,退出永远不会发生,因为你有一个没有中断的“while True”

TA贡献1898条经验 获得超8个赞
实际上,此构造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.
添加回答
举报