1

I have a python script myscript.py on a RaspberryPi with Raspbian that starts on boot via rc.local file. Since it has infinite loop in it I need to run it in background. So far so good but I also want to log this script's stdout to file with a pipe but can't get it working. My rc.local file looks like this:

/usr/bin/python3 /home/pi/myscript.py >> /var/www/html/log.log &

My log.log file has 666 permission so my script should be able to write to it right? Yet it does not.

muliku
  • 185
  • 4
  • 10
  • I think you want to send output to a file within the python script. `import sys sys.stdout = open('file', 'w')`. With the recent bash versions you can do something like `...&>> /var/www/html/log.log &` – Valentin Bajrami Aug 06 '19 at 13:00
  • @ValentinBajrami `import sys sys.stdout = open('file', 'w')` didn't do the trick. It works when run from console but still does not write to the file when run at boot within `rc.local` – muliku Aug 06 '19 at 13:41
  • But that is an `rc.local` thing then. On what system are you running this? – Valentin Bajrami Aug 06 '19 at 18:40

1 Answers1

4

Output of python is buffered by default, you have to use "-u" parameter to avoid buffering. So this should do the trick:

/usr/bin/python3 -u /home/pi/myscript.py >> /var/www/html/log.log &
antrzej
  • 41
  • 2
  • 1
    Kudos for noting this! Many programs do the same thing--standard out is buffered by default (standard error is usually unbuffered) so the kernel does not actually display the buffered output until the buffer is full. This includes output redirection: It's not sent to the redirected file until the buffer is full. Additionally, some programs may do their own buffering before even sending output to the kernel to be displayed-or-buffered by the kernel. – C. M. Apr 22 '21 at 07:54