问题
I am trying to print a string letter by letter (with a pause in between each print) onto the terminal screen and I want it to all be on the same line.
I currently have this:
sleepMode = "SLEEP MODE..."
activ = "ACTIVATE!"
for l in sleepMode:
print(l, end=" ")
sleep(0.1)
sleep(2)
for l in activ:
print(l, end=" ")
sleep(0.1)
For some reason this doesn't sleep in between prints in the loop, rather it seems to wait until the loop is complete before printing all of it out at once.
I want it to look like it is being "typed" on the screen in real time.
Any suggestions?
Thanks! Zach
回答1:
try flushing it
for l in activ:
print(l, end=" ")
sys.__stdout__.flush()
sleep(0.1)
no idea if it will work since I am assuming you are using py3x and it works fine in my system with or without the flush
flush just forces the output buffer to write to the screen ... normally it will wait until it has some free time to dump it to the screen. but sleep was locking it. so by flushing it you are forcing the content to the screen now instead of letting the internal scheduler do it ... at least thats how I understand it. Im probably missing some nuance
回答2:
The following works:
import time
import sys
sleepMode = "SLEEP MODE..."
activ = "ACTIVATE!"
for l in sleepMode:
sys.stdout.write(l);
time.sleep(0.1)
time.sleep(2)
print
for l in activ:
sys.stdout.write(l);
time.sleep(0.1)
来源:https://stackoverflow.com/questions/17433850/how-can-i-print-a-string-using-a-while-loop-with-an-interval-in-between-letters