python - 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。
谢谢!
解决方案
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
.
推荐阅读
- swift - Xcode swift - 复制捆绑后 AVAudio 播放器不工作
- php - Redis 中的 FLUSHALL ASYNC 线程是否安全?
- android - android phone linux deploy docker systemctl 在 chroot 中运行,忽略请求。问题
- php - 如何删除数组前后的“”
- ios - 如何在 Swift 4 中显示没有 UIViewController 的新屏幕?
- encryption - 是否所有功能都属于 FAST API 中可用的 Django Rest Framework 来开发 REST APIS
- cron - 在 12:00 AM 到 12:59 AM 之间每 20 分钟执行一次 Cron 表达式,仅在星期六
- backend - 在没有浏览器的情况下运行 DHTMLX API
- c++ - 单击一个按钮后创建一个按钮
- vue.js - 如果在所选语言文件中没有找到翻译,如何显示英文翻译?