5

Possible Duplicate:
Python Progress Bar

I am running a for loop 10,000 times, but inside the loop there are a lot of calculations going on. I would like to print out a progress message to the console informing me how far along in the loop the program is how much longer I might have to wait.

the basic loop is

n = 10000 
for i in range(n):
   do_stuff_method()
   if(i%100 == 0):
      print (float(i)/n)*100,

This prints out a percentage message on the same line, but the problem is that the next thing that I print out is also printed out on the same screen. That, and since there are 99 prinouts, the console gets pretty wide and there is a lot of scrolling across.

What I would really like is for the console to print out the current % done, and an estimated time to finsih on the one line replace that which had been previously printed, so there doesn't have to be a lot scrolling.

Can this be done?

Cheers, Davy

Community
  • 1
  • 1
Davy Kavanagh
  • 4,809
  • 9
  • 35
  • 50
  • In addition, a package exists for python to do this called... Progress Bar. Check it out from pypi: http://pypi.python.org/pypi/progressbar/2.2 – jmetz Jul 25 '12 at 15:00

1 Answers1

8

In your case you can do it simply by changing your print line to be:

print "\r{0}".format((float(i)/n)*100),

Or you can try it like this instead of print:

sys.stdout.write("\r{0}".format((float(i)/n)*100))
sys.stdout.flush()
iblazevic
  • 2,713
  • 2
  • 23
  • 38
  • I just tested this. It prints each value on a new line. – Davy Kavanagh Jul 25 '12 at 15:12
  • you can try that other solution I put in the answer, both of them work for me – iblazevic Jul 25 '12 at 15:26
  • yep.I tried with and without the comma, and with and without the `\r` but they all just print either on the same line, or on a new line. I was looking for something that prints the new % value over the old % value. – Davy Kavanagh Jul 25 '12 at 15:27
  • I tried the second answer also. Still each value on new line. Weird. Could it be something to do with my console. It's the console inside eclispe on a mac if that makes a difference – Davy Kavanagh Jul 25 '12 at 15:29
  • can't really answer you on that but you can try running it from your regular terminal – iblazevic Jul 25 '12 at 15:32
  • Sorry. I tried it in a regular terminal. The second solution works. Thanks and sorry again for the confusion. – Davy Kavanagh Jul 25 '12 at 15:34
  • no problem as long as it's working – iblazevic Jul 25 '12 at 15:35
  • For the first print command, you can also clear the console by putting "print('\033[H\033[J')", just before the posted print command. That clears the console without needing to use the sys command – Diesel Mar 07 '20 at 19:51