在python3中更新stdout上的打印字符串

时间:2017-10-24 00:57:27

标签: python string format linefeed

我正在尝试使用python和格式化字符串更新打印到stdout的行。该行正在打印,但在每个循环中,它都打印在同一行上,紧接着之前打印的更新。

item = ("{}{}{}{}".format(totalAllScraped, 
                          str(" profiles scraped "),
                          (len(sortedurls)), 
                          str(" filtered profiles saved.")))
print(item, sep='', end='', flush=True)

我想将行打印到stdout,并且循环的每次迭代,前一行都被下一行覆盖。

2 个答案:

答案 0 :(得分:1)

import sys

stuff = ("{}{}{}{}".format(totalAllScraped, str(" profiles scraped "), (len(sortedurls)), str(" filtered profiles saved.")))
    sys.stdout.write("\r" + stuff)
    sys.stdout.flush()
无论如何,这都是诀窍

答案 1 :(得分:0)

这是一个更简单的Python字符串示例,已打印到要替换的stdout

import sys 
import time
for i in range(3):
    message = "testing " + i 
    sys.stdout.write("\r" + stuff)   #The \r is carriage return without a line 
                                     #feed, so it erases the previous line.
    sys.stdout.flush()
    time.sleep(1)

以上版画:

testing 1

对于Stdout,然后2次后续迭代将其删除,并将其替换为“测试2'然后'测试3'。