Search code examples
background-processpython-3.x

Python script run in background not writing to file?


I've created my first ever python script and it works fine in the foreground, but when I run it in the background it creates, but fails to write anything to the file. I run the script with command : python -u testit.py &
Please help me understand why this happens.

#!/usr/bin/env python

import time
import datetime
dt = datetime.datetime.now()
dtLog = dt.strftime("ThermoLogs/TempLOG%Y%m%d")
f = open(dtLog,"a")
while True:
    dt = datetime.datetime.now()
    print('{:%Y-%m-%d %H:%M:%S}'.format(dt))
    f.write('{:%Y-%m-%d %H:%M:%S}'.format(dt))
    f.write('\n')
    time.sleep(5)

Solution

  • The output will arrive in bursts (it is being buffered). With the sleep set to 0.01 I am getting bursts about every 2 seconds. So for a delay of 5 you will get them much less frequent. You may also note that it outputs all pending outputs when you terminate it.

    To make the output arrive now call f.flush().

    I don't see any difference between foreground and background. However it should not buffer stdout when going to a terminal.