将stdout重定向到文件时,Python脚本不输出任何输出 [英] Python script writes no output when stdout is redirected to a file
问题描述
我在树莓派上启动时运行了一个python脚本(运行良好),我想将输出附加到现有的文本文件中.我在/etc/rc.local文件中获得了此代码(我使用cron尝试了相同的操作,但是由于某种原因它甚至没有启动脚本).
I got a python script running on startup on my raspberry pi (which works fine) where I want to append the output to an existing text file. I got this code in my /etc/rc.local file (I tried the same with cron, but there it doesn't even start the script for some reason).
python3 /home/pi/script.py >> /home/pi/log.txt
不幸的是,无论我如何尝试,日志文件始终为空,除非我直接运行同一命令并通过按ctrl + c(而不是ctrl + z)中止脚本.似乎该脚本必须先以正确的方式关闭,然后才能将任何内容写入文件,但我希望它逐步将每一个输出保存到文件中.
Unfortunately, no matter what I try, the log file is always empty, except when I run the same command directly AND abort the script by pressing ctrl+c and not ctrl+z. It seems that the script has to shut down in a correct way before it writes anything to the file, but I want it to gradually save the file with every single output.
我解决了.显然,仅在填充了一定数量的内存或脚本完成后才写入文件是正常的(这对我而言从来没有,因为我总是在可能发生之前重新启动pi).添加-u标志可立即写入文件.
I solved it. Apparently it's normal that the file gets only written after a certain amount of memory is filled or the script is finished (Which it never was in my case, as I always restarted the pi before that could happen). Add the flag -u to instantly write to file.
python3 -u /home/pi/script.py >> /home/pi/log.txt
推荐答案
If you are using print to output text, its argument flush
might help you:
print('Hello, World', flush=True)
否则:
import sys
sys.stdout.write('Hello, world\n')
sys.stdout.flush()
将具有相同的效果.
这篇关于将stdout重定向到文件时,Python脚本不输出任何输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!