nehem
nehem

Reputation: 13672

Python patten for progress count

I often have to run lot of maintenance scripts, I always insert below code to track the progress of any iterable.

c = len(sequence)
i = 1
for s in sequence:
    print "{}/{}".format(i,c)
    i+=1
    # Do something

Are there more elegant & pythonic ways to convert this code as a reusable patten?

Upvotes: 0

Views: 78

Answers (2)

Tadhg McDonald-Jensen
Tadhg McDonald-Jensen

Reputation: 21474

in a word: enumerate:

for i, s in enumerate(sequence):
    print "{}/{}".format(i,c)
    #do stuff

To signal progression out of the total however you will prabably want to start at 1 (enumerate takes start=1 as an argument)

Although if you also find yourself using that exact print statement frequently you can wrap this in a generator.

def verbose_enuemrate(seq):
    total = len(seq)
    #print "starting verbose_enumerate with:", seq
    for i,item in enumerate(seq, start=1):
        print("{}/{}".format(i,total))
        yield i,item
    #print "finished verbose_enumerate of:", seq

>>> for i,c in verbose_enuemrate("abc"):
    print(c)    
1/3
a
2/3
b
3/3
c

Upvotes: 3

Hassan Mehmood
Hassan Mehmood

Reputation: 1402

Try the following code to show progress on the same line.

import time
print "Work in progress(0%%)", # Python 2 print without newline
for work_done in range(10):
    print "\b\b\b\b\b%2d%%)" % work_done, # Backspace then overwrite
    time.sleep(1) # or do some work

Upvotes: 2

Related Questions