Charles Von Franklyn
Charles Von Franklyn

Reputation: 47

Updating a printed string on stdout in python3

I am trying to update a line printed to stdout using python and a formatted string. The line is printing, but on each loop through it prints on the same line, next to the previous printed update.

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

I want to print the line to stdout, and every iteration of the loop, the previous line is overwritten by the next line.

Upvotes: 2

Views: 1683

Answers (2)

Eric Leschinski
Eric Leschinski

Reputation: 153963

Here is a simpler example of Python string having been printed to stdout being replaced

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)

The above prints:

testing 1

To Stdout, then the 2 subsequent iterations erases it and replaces it with 'testing 2' then 'testing 3'.

Upvotes: 1

Charles Von Franklyn
Charles Von Franklyn

Reputation: 47

import sys

stuff = ("{}{}{}{}".format(totalAllScraped, str(" profiles scraped "), (len(sortedurls)), str(" filtered profiles saved.")))
    sys.stdout.write("\r" + stuff)
    sys.stdout.flush()

this did the trick thanks anyway

Upvotes: 1

Related Questions