Problem with python contextmanager newline

Using the Python contextmanager I want to generate a wrapper to display a Linux-like move of a specific block of code:

Doing something... done. [42 ms]

This is a working view:

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 breaking the line, wait a second, print “done. [1000 ms]”, including line break and exit.

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

However, when the fragment starts, the first output expects the second, and then prints the entire line. When deleted end=''in the first expression, print()everything works as expected, but due to the ugly output.

Why is this, is it intended, and what can be done to avoid this behavior?

(Python 3.4.0 on Linux Mint 17.1)

+4
source
1

, , stdout. , . Python 3.3+ print flush:

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))

3.3 flush stdout:

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

All Articles