Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash won't redirect output to a file and run in the background [duplicate]

I've seen many similar questions to this, but the problem is that none of the other solutions have fixed my issue. I want to run 2 python scripts and redirect their output to separate log files using nohup.

This code is located in a bash script called startmain:

nohup python3 GUI.py > GUI.log 2>&1 &
nohup python3 main.py > main.log 2>&1 &

When I run sh startmain, the scripts both execute, but nothing is written to either log file.

Now let's say instead I change the startmain code by removing the & characters at the end of the line:

nohup python3 GUI.py > GUI.log 2>&1
nohup python3 main.py > main.log 2>&1

This code says I don't want the scripts running in the background, so only GUI.py runs; however, here it actually directs all the output from GUI.py to GUI.log. I know why main.py doesn't run here, but I don't know why the output is written to GUI.log in this case but not when I try and run the scripts in the background.

Any idea what my issue is here? What sets my question apart from the similar ones is that I'm executing 2 scripts, which could be a reason why it's not working.

like image 639
Daniel C Jacobs Avatar asked Sep 01 '25 22:09

Daniel C Jacobs


1 Answers

Thanks @KamilCuk for the help!

Adding a -u option fixed the issue:

nohup python3 -u GUI.py > GUI.log 2>&1
nohup python3 -u main.py > main.log 2>&1

But why did this work?

Because by default, the stdout/stderr output is buffered, and only gets flushed at specific intervals (e.g. every 1kB). The "-u" option eliminates the buffer with python and will write the output immediately to the destination.

NOTE: this question is actually a duplicate of nohup-is-not-writing-log-to-output-file

like image 190
Daniel C Jacobs Avatar answered Sep 03 '25 13:09

Daniel C Jacobs