linuxbashloggingnohup

How can I save a log file with nohup command?


I am trying to run a python script in the background in a Raspbian OS. When I use the following command:

nohup python <script> >> log.txt

where <script> is the python file name. The program saves all the outputs in the log.txt, but it only saves them when I terminate the program, as it is a never-ending loop (I know this because I opened another terminal and used tail -f log.txt). Moreover, if I use the following command:

nohup python <script> >> log.txt &

The file log.txt is created but the data does not append. Any suggestions on why is that happening? Thank you in advance!

PS: I tried using sudo in the command in order to know if the error was the permissions, but the result was the same. I also tried &>>, same result.


Solution

  • Two steps:

    Many tools (and python too) use output buffering for optimization: Output is stored until a amount of data is collected (usually multiple of 4KB). And then exact this block is output. python supports option -u.

    Maybe you have to save stderr too (2>&1 behind redirection).

    So my solution is:

    nohup python -u <script> >> log.txt 2>&1 &
    #            ^^                     ^^^^