简体   繁体   English

如何在不打印到新行的情况下将输出更新到命令行?

[英]How do I update output to the command line without printing to a new line?

I'd like to do things like make updating progress bars and realtime counts of files processed, but I don't want it to span hundreds of line. 我想做一些事情,如更新进度条和处理的文件的实时数,但我不希望它跨越数百行。

Specifically, I'm processing about 6500 emails and it takes several minutes. 具体来说,我正在处理大约6500封电子邮件,需要几分钟时间。 I'd like to print how many have been processed without it taking 6500 lines. 我想打印已经处理了多少已经处理了6500行。

I've seen some solutions in Python 2, but I haven't been able to figure it out in Python 3. 我在Python 2中看到了一些解决方案,但我无法在Python 3中找到它。

You should print it using sys.stdout with carriage return '\\r' . 您应该使用带回车符'\\r' sys.stdout打印它。 Here you have an example: 这里有一个例子:

import time
import sys

for i in range(100):
    sys.stdout.write(str(i+1) + '%\r')
    sys.stdout.flush()
    time.sleep(0.1)

Try it out! 试试看!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM