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

What I wanted was to print 5 dots that print dots per second using time.sleep (), but the result was printed 5 dots immediately after a delay of 5 seconds.
Tried both print and sys.stdout.write, same result.

Thanks for any advice.

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.'
+5
source share
2 answers

You need to flash after recording.

sys.stdout.write('foo')
sys.stdout.flush()
wastetime()
sys.stdout.write('bar')
sys.stdout.flush()
+8
source

You should use sys.stderr.writefor progress indicators; stderr has the (not exactly matching) advantage of not buffering, so there are no calls sys.stderr.flush.

See also this answer.

+4

All Articles