1

I have a Python script like the following:

#!/usr/bin/env python

print("Start")
sql = get_sql_from_file(...)
# The following function takes a long time to run
execute_oracle_driver(sql)
print("Finished")

I execute it with:

(my-env) $ time nohup python script.py &

Then I check if there's any initial output, but nothing:

(my-env) $ cat nohup.out
(my-env) $ 

I would at least expect to see "Start" after no more than a few seconds. Even after waiting a few minutes, then killing it, I get no output. If possible, how can I fix this?

Wassadamo
  • 1,176
  • 12
  • 32
  • Not _at all_ specific to `nohup`. This happens by default _whenever_ stdout is redirected to a file by any means whatsoever. – Charles Duffy Jul 08 '20 at 22:39
  • ...it's not even specific to Python. There's a C++ version of this question at https://stackoverflow.com/questions/21389796/program-will-not-print-line-before-exit-function, and an excellent BashFAQ entry about it at [BashFAQ #9](https://mywiki.wooledge.org/BashFAQ/009). – Charles Duffy Jul 08 '20 at 22:42
  • My apologies. I was unaware of how buffering worked (thanks for the link), and thought this was due to some combination of Python and nohup. – Wassadamo Jul 08 '20 at 23:18
  • 1
    BTW, *how* are you killing your program after a few minutes? If you use a TERM instead of a KILL, it should flush its output then. (This is part of why sysadmins have been telling people for pretty much ever not to use `kill -9` except as a last resort; programs can't flush their buffers, clean up their SHM segments and temporary files, or otherwise do any of the work needed to exit gracefully when terminated that way). – Charles Duffy Jul 08 '20 at 23:39
  • 1
    I was using `kill -9`. Looks like `kill -s TERM ` is a [better approach](https://superuser.com/a/406926/534123). – Wassadamo Jul 09 '20 at 00:01
  • 1
    Or just `kill `, which defaults to TERM. – Charles Duffy Jul 09 '20 at 00:14

1 Answers1

3

Output is buffered by default, so you would need to ensure that the output is flushed; otherwise, no output will be seen in nohup.out until the end of the program. One way to do that is as follows:

print("Start", flush=True)
Anthony Tuininga
  • 6,388
  • 2
  • 14
  • 23
  • In [How to Answer](https://stackoverflow.com/help/how-to-answer), note the section *Answer Well-Asked Questions*, and therein the bullet point regarding questions that "have been asked and answered many times before". – Charles Duffy Jul 08 '20 at 22:41