Proprio per unire tutte le risposte di cui sopra in un insieme di funzioni di utilità utile perché un requisito fondamentale della OP (e me!) È "because I don't want to write outputFile.flush() each time":
import os
import tempfile
import time
def write_now(filep, msg):
"""Write msg to the file given by filep, forcing the msg to be written to the filesystem immediately (now).
Without this, if you write to files, and then execute programs
that should read them, the files will not show up in the program
on disk.
"""
filep.write(msg)
filep.flush()
# The above call to flush is not enough to write it to disk *now*;
# according to https://stackoverflow.com/a/41506739/257924 we must
# also call fsync:
os.fsync(filep)
def print_now(filep, msg):
"""Call write_now with msg plus a newline."""
write_now(filep, msg + '\n')
# Example use with the with..as statement:
with tempfile.NamedTemporaryFile(prefix='some_prefix_here.', suffix='.log', dir='.', delete=False) as logf:
print_now(logf, "this is a test1")
time.sleep(20)
print_now(logf, "this is a test2")
Grazie, la seconda opzione è la migliore per me perché non desidero scrivere outputFile.flush() ogni volta, ma entrambe funzionano. – elbajo
Invece di lasciare il file aperto durante operazioni a tempo intensivo, potrebbe valere la pena di prendere in considerazione l'istruzione with che realizzerebbe la stessa cosa. – nachshon
@nachshon "realizza la stessa cosa": non per me sul mio sistema (RHEL 6.8 con [conda] (https://en.wikipedia.org/wiki/Conda_ (package_manager)) basato su Python 2.7.13). La chiamata 'os.fsync()' menzionata nella risposta [ffeast] (https://stackoverflow.com/a/41506739/257924) è richiesta (non posso dire con certezza per Python basato su Microsoft Windows o altri sistemi operativi). – bgoodr