python contextmanager newline issue

廉价感情. 提交于 2019-11-29 14:39:35

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()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!