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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With