42

我意识到,当我使用 python 写入文件时,它会等到我的 Python 文件末尾执行它:

outputFile = open("./outputFile.txt","a")
outputFile.write("First")
print "Now you have 10sec to see that outputFile.txt is still the same as before"
time.sleep(10)
outputFile.write("Second")
print "Now if you look at outputFile.txt you will see 'First' and 'Second'"

我如何让 python 立即写入输出文件?

4

4 回答 4

73

您可以使用flush()或将文件对象设置为无缓冲。

open() 有关在此处使用该参数的详细信息。

因此,您可以将公开电话更改为-

outputFile = open("./outputFile.txt", "a", 0)
于 2013-09-24T14:19:22.963 回答
26

用函数强制它flush(),添加

outputFile.flush()

在您的代码末尾。

于 2013-09-24T14:17:18.240 回答
8

正如@RyPeck 所说,您可以使用flush()或将文件对象设置为无缓冲。但请注意以下内容(来自 https://docs.python.org/2/library/stdtypes.html?highlight=file%20flush#file.flush):

刷新内部缓冲区,如 stdio 的 fflush()。

注意 flush() 不一定将文件的数据写入磁盘。使用 flush() 后跟 os.fsync() 来确保这种行为。

并引用man 3 fflush

请注意, fflush() 仅刷新 C 库提供的用户空间缓冲区。为确保数据物理存储在磁盘上,内核缓冲区也必须刷新,例如使用 sync(2) 或 fsync(2)。

于 2017-01-06T13:25:39.233 回答
8

只是将所有上述答案组合成一组有用的实用程序函数,因为OP(和我自己!)的一个关键要求是“因为我不想每次都写 outputFile.flush() ”:

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")
于 2017-08-16T15:27:25.787 回答