树莓派5中crontab无法将Python程序标准输出重定向至文件
问题解决:树莓派5 cron @reboot 仅捕获Python脚本stderr输出
问题原因
Python在非交互式终端(比如cron的执行环境)中,stdout默认是块缓冲模式,只有当缓冲区满或者程序结束时才会写入文件;而stderr默认是无缓冲,会实时输出。你的脚本是无限循环,程序不会结束,所以stdout的内容一直留在缓冲区里,没写入日志文件。而普通bash环境是交互式的,stdout默认是行缓冲,所以能实时看到输出。
解决方法
方法1:Python启动时禁用缓冲
在crontab的命令里给python3加上-u参数,强制stdout无缓冲:
@reboot /usr/bin/python3 -u /home/pi/test.py >> /home/pi/cronlog.log 2>&1
方法2:修改Python脚本手动刷新输出
在脚本里每次写入stdout后手动刷新缓冲区,或者开启行缓冲:
方式A:每次写入后刷新
import time import sys while True: time.sleep(1) sys.stdout.write("out\n") sys.stdout.flush() # 手动刷新stdout sys.stderr.write("err\n")
方式B:开启行缓冲
在脚本开头设置stdout的行缓冲属性:
import time import sys sys.stdout.line_buffering = True # 开启行缓冲 while True: time.sleep(1) sys.stdout.write("out\n") sys.stderr.write("err\n")
方法3:在crontab中设置环境变量
在crontab里添加PYTHONUNBUFFERED=1环境变量,让Python默认无缓冲:
PYTHONUNBUFFERED=1 @reboot /usr/bin/python3 /home/pi/test.py >> /home/pi/cronlog.log 2>&1
验证方法:修改后重启树莓派,等待几分钟后查看/home/pi/cronlog.log,应该能同时看到out和err的内容。
内容的提问来源于stack exchange,提问作者unfestive chicken
相关产品推荐
相关产品推荐

