Problems with sys.stdout.write() with time.sleep() in a function

岁酱吖の 提交于 2019-12-30 09:37:16

问题


What I wanted is printing out 5 dots that a dot printed per a second using time.sleep(), but the result was 5 dots were printed at once after 5 seconds delay.
Tried both print and sys.stdout.write, same result.

Thanks for any advices.

import time
import sys

def wait_for(n):
    """Wait for {n} seconds. {n} should be an integer greater than 0."""
    if not isinstance(n, int):
        print 'n in wait_for(n) should be an integer.'
        return
    elif n < 1:
        print 'n in wait_for(n) should be greater than 0.'
        return
    for i in range(0, n):
        sys.stdout.write('.')
        time.sleep(1)
    sys.stdout.write('\n')

def main():
    wait_for(5)    # FIXME: doesn't work as expected

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print '\nAborted.'

回答1:


You need to flush after writing.

sys.stdout.write('foo')
sys.stdout.flush()
wastetime()
sys.stdout.write('bar')
sys.stdout.flush()



回答2:


You should use sys.stderr.write for progress bars; stderr has the (not at all coincidental) advantage of not being buffered, so no sys.stderr.flush calls are needed.

See also this answer.



来源:https://stackoverflow.com/questions/2808832/problems-with-sys-stdout-write-with-time-sleep-in-a-function

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