views:

127

answers:

2

I was wondering how often python flushes to a file. Also wondering how often python flushes to stdout. I believe python flushes to stdout after every new line but that being said, if you overload stdout to be to a file does it flush as often as stdout or how often it flushes to a file?

Anyways thanks! And sorry for the pretty simple question!

edit: Corrected spelling of does... Whoops

+3  A: 

I don't know if this applies to python as well, but I think it depends on the operating system that you are running.

On Linux for example, output to terminal flushes the buffer on a newline, whereas for output to files it only flushes when the buffer is full (by default). This is because it is more efficient to flush the buffer fewer times, and the user is less likely to notice if the output is not flushed on a newline in a file.

You might be able to auto-flush the output if that is what you need.

EDIT: I think you would auto-flush in python this way (based from here)

#0 means there is no buffer, so all output
#will be auto-flushed
fsock = open('out.log', 'w', 0)
sys.stdout = fsock
#do whatever
fsock.close()
KLee1
+2  A: 

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 bufsize 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 bufsize 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."

bufize = 0
f = open('file.txt', 'w', bufsize)
Corey Goldberg