python contextmanager newline issue -


using python's contextmanager want generate wrapper display linux-like progress of block of code:

doing something... done. [42 ms]

this working - kind of:

from contextlib import contextmanager import time  @contextmanager def msg(m):     print(m + "... ", end='')     t_start = time.time()     yield     t_duration_ms = 1000 * (time.time() - t_start)     print("done. [{:.0f} ms]".format(t_duration_ms)) 

this usage example should print "doing something... " without line break, wait second, print "done. [1000 ms]" including line break , quit.

with msg("doing something"):     time.sleep(1) 

however, when running snippet, output first waits second, , afterwards prints whole line. when removing end='' @ first print() statement works expected, @ cost of ugly output.

why case, intended, , done avoid behavior?

(python 3.4.0 on linux mint 17.1)

the problem due buffering of stdout. need manually flush message displayed. in python 3.3+, print function has flush argument:

from contextlib import contextmanager import time  @contextmanager def msg(m):     print(m + "... ", end='', flush=true)     t_start = time.time()     yield     t_duration_ms = 1000 * (time.time() - t_start)     print("done. [{:.0f} ms]".format(t_duration_ms)) 

prior 3.3, have use flush method of stdout:

print(m + "... ", end='') sys.stdout.flush() 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -