所以这是一些应该打印文本的代码,类似于口袋妖怪的做法。纯粹是为了好玩。
问题是当程序在终端中运行时“print(x,end =”“)”不起作用,但在使用IDLE运行时它可以正常工作。
import time
lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque id feugiat leo. Quisque dictum, lectus dictum facilisis porttitor, diam dui sagittis nisl, et ultricies nisi dolor eget mauris. Integer euismod aliquam imperdiet. Nulla id orci elit. Nulla quis viverra diam, in lobortis urna. Integer lorem lectus, feugiat vel placerat et, ornare at urna. Praesent nec nisi venenatis, feugiat quam eget, tristique tellus. Fusce in magna tincidunt, lacinia turpis eu, porta ex. Phasellus ullamcorper, elit consectetur convallis imperdiet, nunc magna imperdiet nulla, quis porta dolor neque at dolor. Cras dolor nisl, tristique eget placerat vel, aliquet at nisl. Ut finibus interdum libero a luctus."
for x in lorem:
print(x, end = "")
time.sleep(0.03)
由于某些原因,如果我在“print(x,end =”“)”之前放置一个print语句,程序就可以正常工作。
for x in lorem:
print()
print(x, end = "")
time.sleep(readSpeed)
有谁知道造成这种情况的原因是什么?也许如何解决它?感谢!!!
答案 0 :(得分:2)
这是因为python使用缓冲区写入stdout。为了获得所需的效果,您必须将sys.stdout.flush()放在代码的末尾...
import time, sys
lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque id feugiat leo. Quisque dictum, lectus dictum facilisis porttitor, diam dui sagittis nisl, et ultricies nisi dolor eget mauris. Integer euismod aliquam imperdiet. Nulla id orci elit. Nulla quis viverra diam, in lobortis urna. Integer lorem lectus, feugiat vel placerat et, ornare at urna. Praesent nec nisi venenatis, feugiat quam eget, tristique tellus. Fusce in magna tincidunt, lacinia turpis eu, porta ex. Phasellus ullamcorper, elit consectetur convallis imperdiet, nunc magna imperdiet nulla, quis porta dolor neque at dolor. Cras dolor nisl, tristique eget placerat vel, aliquet at nisl. Ut finibus interdum libero a luctus."
for x in lorem:
print(x, end = "")
time.sleep(0.03)
sys.stdout.flush()
这将以每0.03秒1个字符的速率单独打印每个字符