[英]sys.stdout.write and sys.stdout.flush leave characters behind
I'm trying to make a counter that ticks down from 1,000,000 to 0 in increments of 100,000 per second and displays this on one line, updating each second. 我正在尝试制作一个计数器,该计数器以每秒100,000的增量从1,000,000滴答到0,并将其显示在一行上,每秒更新一次。
However, the below code prints an extra zero at the end: 但是,下面的代码在末尾打印一个额外的零:
counter = 1000000
while counter > 0:
sys.stdout.write("%s\r" % counter)
sys.stdout.flush()
counter -= 100000
time.sleep(1)
I get the output (each writing over the previous line): 我得到输出(每个写在上一行):
1000000
9000000
8000000
7000000
6000000
...
The script stops correctly at the end. 脚本最后正确停止。 When I replace \\r
with \\n
it prints the numbers correctly, but obviously I want it to refresh rather than create a new line each time. 当我用\\n
替换\\r
,它会正确打印数字,但是显然我希望它刷新而不是每次都创建新行。
Last character is left from the first line, as a workaround you could overwrite it manually: 第一行剩下最后一个字符,作为解决方法,您可以手动覆盖它:
while counter > 0:
sys.stdout.write(str(counter).ljust(7) + "\r")
counter -= 100000
time.sleep(1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.