python contextmanager newline issue

后端 未结 1 1291
不知归路
不知归路 2020-12-21 04:22

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]

相关标签:
1条回答
  • 2020-12-21 05:11

    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()
    
    0 讨论(0)
提交回复
热议问题