python - 标准输出和冲洗?它是追加而不是冲洗

标签 python

我想做的是在我创建的脚本底部添加一些“进度文本”。如果我 for 循环一个列表 [1,2,3,4,5] 并打印 i,那么它只是在不同的行上打印 1,2,3,4 和 5。如果我想在屏幕上打印 1,休眠 5 秒,清除它然后打印 2,怎么样?

我试过使用 stdout.write("text")、sleep、flush、stdout.write("aetlkjetjer")、sleep,它只是简单地添加到“text”语句上,而不是刷新输出。

我对 stdout.flush 的工作方式有什么误解吗?它不是应该刷新/删除先前打印的输出吗?

最佳答案

所有 .flush() 所做的就是清除缓冲区。您真正想要的是将退格键(\b) 写入stdout

import time, sys

for i in [1,2,3,4,5]:
    sys.stdout.write(str(i))
    sys.stdout.flush() #flush the buffer because python buffers stdout
    time.sleep(5)
    sys.stdout.write("\b") #literally "write backspace".
    sys.stdout.flush()

如果你想对多于一位数的数字进行计数,它会变得更加复杂。

关于python - 标准输出和冲洗?它是追加而不是冲洗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31172195/

相关文章:

python - 如何让这个 Python 质数查找程序更加有用?

python - 网站加载时如何检查django项目中的用户IP?

python - django 的分页器中的孤儿是什么意思?

python - 如何使用 python stomp.py 客户端在 activemq 中安排延迟消息

python - ValueError : n_components=4 must be between 0 and min(n_samples, n_features)=2 与 svd_solver ='full'

python - 在raspberrypi上使用python将arduino的数据存储在mysql中

python - 文件扩展名命名 : . p vs .pkl vs .pickle

python - Pyspark 增加了几秒的时间

python - Youtube API : Adding videos to a playlist with the new 32 character playlist ID

python - 是否可以获取字段的所有参数