Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 
like image 870
Synapsen Salat Avatar asked Jul 05 '18 20:07

Synapsen Salat


1 Answers

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.

like image 83
Eugene Primako Avatar answered Oct 16 '22 09:10

Eugene Primako