0

I'm using Python 2.7.3 and I running the code below

def t2():
    print "Waiting...",
    time.sleep(3)
    print "done."
    time.sleep(1)
    print "test"
    time.sleep(2)
    print "testing"

When I run this code, the string "Waiting... done." appear at same time. It's like the sleep(2) is before the first print.

If I don't use comma to remove new line (Like "test" and "testing" examples), sleep function works ok but I get "Waiting..." and "done." on different lines.

I already tried:

for i in range(0, 5): time.sleep(1)

and

subprocess.check_output(["sleep", "5"])

What can I do?

Thank you.

Victor Santos
  • 350
  • 1
  • 4
  • 14

1 Answers1

0

Depending what you are working with data doesn't necessarily get written right away. In particular, display output often waits until it receives a newline before printing anything.

flush() makes sure it all gets written right now.

Background reading that helps explain better than I can: Usage of sys.stdout.flush() method

Community
  • 1
  • 1