My favorites | Sign in
Project Home Downloads Wiki Source
Checkout   Browse   Changes    
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#!/usr/bin/env python
#
# Corey Goldberg - 2010
# ascii command-line progress bar with percentage and elapsed time display
#



import sys
import time



class ProgressBar:
def __init__(self, duration):
self.duration = duration
self.prog_bar = '[]'
self.fill_char = '#'
self.width = 40
self.__update_amount(0)

def animate(self):
for i in range(self.duration):
if sys.platform.lower().startswith('win'):
print self, '\r',
else:
print self, chr(27) + '[A'
self.update_time(i + 1)
time.sleep(1)
print self

def update_time(self, elapsed_secs):
self.__update_amount((elapsed_secs / float(self.duration)) * 100.0)
self.prog_bar += ' %ds/%ss' % (elapsed_secs, self.duration)

def __update_amount(self, new_amount):
percent_done = int(round((new_amount / 100.0) * 100.0))
all_full = self.width - 2
num_hashes = int(round((percent_done / 100.0) * all_full))
self.prog_bar = '[' + self.fill_char * num_hashes + ' ' * (all_full - num_hashes) + ']'
pct_place = (len(self.prog_bar) / 2) - len(str(percent_done))
pct_string = '%d%%' % percent_done
self.prog_bar = self.prog_bar[0:pct_place] + \
(pct_string + self.prog_bar[pct_place + len(pct_string):])

def __str__(self):
return str(self.prog_bar)




if __name__ == '__main__':
""" example usage """

# print a static progress bar
# [########## 25% ] 15s/60s

p = ProgressBar(60)
p.update_time(15)
print 'static progress bar:'
print p


# print a static progress bar
# [=================83%============ ] 25s/30s

p = ProgressBar(30)
p.fill_char = '='
p.update_time(25)
print 'static progress bar:'
print p


# print a dynamic updating progress bar on one line:
#
# [################100%##################] 10s/10s
# done

secs = 10
p = ProgressBar(secs)
print 'dynamic updating progress bar:'
print 'please wait %d seconds...' % secs

# spawn asych (threads/processes/etc) code here that runs for secs.
# the call to .animate() blocks the main thread.

p.animate()

print 'done'


"""
example output:


$ python progress_bar.py

static progress bar:
[########## 25% ] 15s/60s

static progress bar:
[=================83%============ ] 25s/30s


dynamic updating progress bar:

please wait 10 seconds...

[################100%##################] 10s/10s
done

"""

Change log

r527 by cgoldberg on Jun 20, 2011   Diff
updates
Go to: 

Older revisions

r526 by cgoldberg on Jun 20, 2011   Diff
updates
r371 by cgoldberg on Jan 2, 2011   Diff
[No log message]
r346 by cgoldberg on Jan 2, 2011   Diff
[No log message]
All revisions of this file

File info

Size: 2706 bytes, 112 lines
Powered by Google Project Hosting