io redirection - Python: contextlib.redirect_stdout sometimes doesn't work in real time -


i using python3.5 on ubuntu. following script creates file out , fills more , more lines of "hello":

import contextlib contextlib.redirect_stdout(open('out','w')):     while true:         print('hello') 

however, if make tiny modification adding call time.sleep(), file out stays empty:

import contextlib import time contextlib.redirect_stdout(open('out','w')):     while true:         print('hello')         time.sleep(1) 

if further change code turning loop finite loop, fills out in lump @ end of loop.

can reproduce , explain it?

this caused output buffering. interesting case given use of contextlib, underlying issue open('out', 'w') statement.

to prevent output buffering, can set buffering argument 0 if you're using python 2:

import contextlib import time  contextlib.redirect_stdout(open('out','w', 0)):     while true:         print 'hello'         time.sleep(1) 

alternatively, file contents written once context manager closes file (or once buffered content exceeds size).

if you're using python 3, can't have unbuffered text i/o (kindly pointed out in comments). however, flushing stdout @ end of each loop should have desired effect:

import contextlib import time import sys  contextlib.redirect_stdout(open('out','w')):     while true:         print('hello')         sys.stdout.flush()         time.sleep(1) 

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -