14

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 
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Synapsen Salat
  • 171
  • 1
  • 5
  • is there text being written anywhere else (i.e., the command line)? what commands in your file do you expect to create text? – jeremysprofile Jul 05 '18 at 20:27
  • 3
    BTW, you should answer your own questions with the "Add an Answer" question, not by editing answer text into the question itself. That way answers can be voted on, commented on, etc. independent of the question itself. – Charles Duffy Jul 05 '18 at 21:00

1 Answers1

7

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.

Eugene Primako
  • 2,767
  • 9
  • 26
  • 35