As per the docs
first do
f.flush(), and then doos.fsync(f.fileno()), to ensure that all internal buffers associated with f are written to disk.
Here is an example,
import os
with open("filename", "w") as f:
while True: # infinite program
f.write("the text")
f.flush()
os.fsync(f.fileno())
Answer from Shadow on Stack OverflowAs per the docs
first do
f.flush(), and then doos.fsync(f.fileno()), to ensure that all internal buffers associated with f are written to disk.
Here is an example,
import os
with open("filename", "w") as f:
while True: # infinite program
f.write("the text")
f.flush()
os.fsync(f.fileno())
1) Get the PID of your python process
pgrep python
2) List file descriptors
ls -l /proc/{PID}/fd
3) Open gdb
$ gdb
(gdb) attach {PID}
(gdb) call fflush({FILE_DESCRIPTOR})
(gdb) detach
4) Check your file
Writing to File Using Buffer In Python - Stack Overflow
How often does python flush to a file? - Stack Overflow
Python writes to a buffer instead of a file - Stack Overflow
Buffer protocol types
For file operations, Python uses the operating system's default buffering unless you configure it do otherwise. You can specify a buffer size, unbuffered, or line buffered.
For example, the open function takes a buffer size argument.
http://docs.python.org/library/functions.html#open
"The optional buffering argument specifies the file’s desired buffer size:"
- 0 means unbuffered,
- 1 means line buffered,
- any other positive value means use a buffer of (approximately) that size.
- A negative buffering means to use the system default, which is usually line buffered for tty devices and fully buffered for other files.
- If omitted, the system default is used.
code:
bufsize = 0
f = open('file.txt', 'w', buffering=bufsize)
You can also force flush the buffer to a file programmatically with the flush() method.
with open('out.log', 'w+') as f:
f.write('output is ')
# some work
s = 'OK.'
f.write(s)
f.write('\n')
f.flush()
# some other work
f.write('done\n')
f.flush()
I have found this useful when tailing an output file with tail -f.
Looks like it writes the output to some buffer
That's correct. You can disable this with flush=True, so:
while True:
print('tick', flush=True)
time.sleep(5)
Try this:
with open('log.log', 'w+') as log_file:
print('tick', file=log_file)
In that way the print output will go to file instead stdout