Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python `print` does not work in loop

I have multi loops in together and a sleep in the most inner loop. for example:

from time import sleep

for i in range(10):
    print i,
    for j in range(-5,5):
        if j > 0:
            print '.',
        else:
            print 'D',
        sleep(1)
    print ''

if you run the code, you may expected to get i value after it D sleep 1 second and another D and again sleep until to the end.

but the result is difference, it waits 10 seconds and prints the whole line of 0 D D D D D D . . . . and waiting again to printing next line.

I found the comma at the end of printing causes this problem. How can I solve it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Because of existence of comma, the output buffers until a .

You should flush the stdout after every print or use sys.stdout.write and flush buffer.

Define your print method:

import sys

def my_print(text):
    sys.stdout.write(str(text))
    sys.stdout.flush()

and at the end of line print a


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...