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.
添加回答
舉報