就上述所有的答案组合成一套有用的实用功能,因为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