2

I am using following code to display string with loop completition percentage:

for x in range(y,z):
    completed = 100*(x-y)/(z-y)
    sys.stdout.write(f'{completed:10.0f}% completed.'
    sys.stdout.flush()

And I want all the strings to be displayed in the same line of windows cmd (earlier value removed, and new printed in same place)

Output I want to obtain, should look like this:

    x% completed.

Where x value is updated with each iteration.

But the output i get looks like this:

    0% completed.         1% completed.         2% completed. ...etc

From what i found it should work on other platforms than Windows, but I am interested about Windows solution.

w8eight
  • 605
  • 1
  • 6
  • 21
  • Similar question: https://stackoverflow.com/questions/3419984/print-to-the-same-line-and-not-a-new-line-in-python – Felipe Sulser Jun 04 '19 at 13:02
  • While digging i only found https://stackoverflow.com/questions/5419389/how-to-overwrite-the-previous-print-to-stdout-in-python Do you mind to share what you input into search? – w8eight Jun 04 '19 at 13:12
  • This is what I googled: "python terminal print same line" – Felipe Sulser Jun 04 '19 at 13:25

1 Answers1

0

add \r at the end of the string:

for x in range(y,z):
    completed = 100*(x-y)/(z-y)
    sys.stdout.write(f'{completed:10.0f}% completed.  \r'
    sys.stdout.flush()

unless you have some buffering issues you should be able to use print directly:

for x in range(y,z):
    completed = 100*(x-y)/(z-y)
    print(f'{completed:10.0f}% completed.  ', end='\r')
mikaël
  • 453
  • 3
  • 8