elb*_*ajo 38 python python-2.7
我意识到当我使用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'"
Run Code Online (Sandbox Code Playgroud)
我怎么想让python立即写入输出文件?
RyP*_*eck 63
您可以使用flush()或者可以将文件对象设置为无缓冲.
有关在open() 此处使用该参数的详细信息.
所以你会改变你的公开电话 -
outputFile = open("./outputFile.txt", "a", 0)
Run Code Online (Sandbox Code Playgroud)
ism*_*ail 18
使用该flush()功能强制它,添加
outputFile.flush()
Run Code Online (Sandbox Code Playgroud)
在代码的最后.
正如@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).
只是将上述所有答案组合成一组有用的实用程序函数,因为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 /sf/answers/2905471761/ 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")
Run Code Online (Sandbox Code Playgroud)