0

What I'm trying to code is pretty simple:

I want to print an iteration variable, but I don't want all the lines printed for each loop, I want that will update the previous one.

Example:

for i in range(0,2000):
   print 'number is %d', %i 

Wrong result:

number is 0
number is 1
number is 2
number is 3
number is 4
number is 5
number is 6
...
...

What I want is:

number is 0 

At the second iteration:

number is 1 `(it will replace 0 and I don't want the previous 0 anymore).`

It will be something like updating percentage of something in only one line.

Does a function exist for it in Python?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
rablo
  • 15
  • 1
  • 5

3 Answers3

4

This will do the trick, and update every 1 second:

import sys
import time

for i in range(0,2000):
    sys.stdout.write('\rnumber is %d' %i)
    sys.stdout.flush()
    time.sleep(1)
Taufiq Rahman
  • 5,600
  • 2
  • 36
  • 44
0

What you want is called the Carriage Return, or \r

Use:

for i in range(0,2000):
    print "number is %d       \r" %i,

The spaces will keep the line clear from prior output.

Divins Mathew
  • 2,908
  • 4
  • 22
  • 34
0

You can try something from this thread on clearing the terminal, or something from the one that fuglede posted as duplicated.

The following code worked fine for me in a mac, but if you remove the time.sleep() it will just run so fast that you wont even see the prints.

import time, sys

for i in range(0, 20):
    print 'Number is: %d' % i
    time.sleep(.1)
    sys.stderr.write("\x1b[2J\x1b[H")
Community
  • 1
  • 1
Chagaf
  • 1