Python sys.stdout.write() strange behavior in Mac terminal
Question: I am trying to make a progress bar for a process, but to keep things short
consider the following snippet:

    
    
    import sys
    import time
    
    for i in range(10):
      time.sleep(0.5)
      sys.stdout.write('*')
    sys.stdout.write('\n')
    

What I am expecting it to do is to print a star every half a second on the
same line (which is exactly what it does when I run the code with an IDE like
Sublime Text for example). However, when I run this in the Mac OS Terminal it
just waits for 5 seconds then prints the whole string `**********` at once.

Any ideas why this might be happening and how to get the desired behavior?


Answer: It does that because output is buffered. Try this instead:

    
    
    import sys
    import time
    
    for i in range(10):
        time.sleep(0.5)
        sys.stdout.write('*')
        sys.stdout.flush()    # <-- this is the key
    sys.stdout.write('\n')
    

By flushing output each time you do a write, `sys.stdout` won't wait for the
next newline; instead it will write whatever characters are in its buffers
immediately.

