Python script writes no output when stdout is redirected to a file [duplicate]

折月煮酒 提交于 2020-08-04 06:50:42

问题


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 

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.

Edit: 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 

回答1:


If you are using print to output text, its argument flush might help you:

print('Hello, World', flush=True)

Otherwise:

import sys
sys.stdout.write('Hello, world\n')
sys.stdout.flush()

will have the same effect.



来源:https://stackoverflow.com/questions/51199339/python-script-writes-no-output-when-stdout-is-redirected-to-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!