2

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.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335

2 Answers2

1
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

  • 1
    Per the comment on the question, you may have been able to remove the `end=''`, which would have ended each print statement with a null rather than an endline. Replacing it with `end="\r"` or `end = '\r'` may also do the trick. – LightCC Oct 24 '17 at 02:28
  • ok thank you very much for taking the time to explain that to me – Charles Von Franklyn Oct 24 '17 at 05:24
1

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'.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335