Search code examples
pythonprintingoutputdelay

Why is there no delay between same-line printing?


print 'foo',
time.sleep(1)
print 'bar'

This seems to run time.sleep(1) first, then prints "foo bar" all at once.

However, printing both foo and bar on its own lines produces the expected delay between the print statements:

print 'foo'
time.sleep(1)
print 'bar'

Is there something that stacks all print statements until a new line character is received?


Solution

  • print by default prints to sys.stdout and it is line-buffered. you could flush the buffer each time after a print statement

    import time
    import sys
    
    print 'foo'
    sys.stdout.flush()
    time.sleep(1)
    print 'bar
    

    reference: sys

    read also: How to flush output of Python print?