Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

python contextmanager newline issue

Using Python's contextmanager I want to generate a wrapper to display Linux-like progress of a certain block of code:

Doing something... done. [42 ms]

This is 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 a line break, wait for a second, print "done. [1000 ms]" including a line break and quit.

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

However, when running the snippet, the output first waits for a second, and afterwards prints the whole line. When removing end='' at the first print() statement everything works as expected, but at the cost of an ugly output.

Why is this the case, is this intended, and what could be done to avoid this behavior?

(Python 3.4.0 on Linux Mint 17.1)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is probably due to buffering of stdout. You need to manually flush it for the message to be displayed. In Python 3.3+, the print function has a 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 to 3.3, you would have to use the flush method of stdout:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...