就上述所有的答案組合成一套有用的實用功能,因爲OP的一個關鍵要求(和我!)是「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")
謝謝,第二個選項對我來說是最好的,因爲我不想每次都寫outputFile.flush(),但兩者都可以工作。 – elbajo
而不是在時間密集型操作中將文件打開,可能值得考慮with語句來完成同樣的事情。 – nachshon
@nachshon「完成相同的事情」:不適合我在我的系統上(RHEL 6.8使用[conda](https://en.wikipedia.org/wiki/Conda_(package_manager)) - 基於Python 2.7.13)。在[ffeast](https://stackoverflow.com/a/41506739/257924)中提到的'os.fsync()'調用是必需的(不能肯定地說明基於Microsoft Windows的Python或其他操作系統的)。 – bgoodr