#Python Program Not Printing Output in nohup
nohup is used to prevent a program from terminating when the terminal hangs up. It’s particularly useful for running long-running tasks.
nohup command &
When you run a program with nohup, standard output and standard error are redirected to nohup.out by default.
You can use the tail -f nohup.out command to monitor the program output in real time.
However, if you use nohup to run a Python script, you may notice that nohup.out shows no output for a long time.
nohup script.py &
This happens because when Python runs in interactive mode, stdout and stderr are line-buffered, but in non-interactive mode, stdout uses block buffering.
- Block buffering: Output is written only when the buffer is full
- Line buffering: Output is written when the buffer is full or a newline character is encountered
As a result, unless the buffer is flushed (i.e., filled and written), you won’t see the standard output in nohup.out.
#Solutions
#Disable buffering
Run the Python script with the -u flag to disable output buffering. Note that this may reduce performance.
nohup python -u script.py &
#Manually set line buffering
You can use the sys.stdout.reconfigure method to manually enable line buffering for standard output:
import sys
sys.stdout.reconfigure(line_buffering=True)