1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 import sys
17 import time
18
19
21
22 """A simplete progress bar class. See example in main below."""
23
24 - def __init__(self, prompt='working: ', endTag=' - done',
25 finalSize=100.0, finalBarLength=10,
26 barChar='#', stream=sys.stdout, redrawYN=1):
27
28
29
30 redrawYN = 0
31
32 self.size = 0.0
33 self.barLength = 0
34 self.barLengthPrinted = 0
35 self.prompt = prompt
36 self.endTag = endTag
37 self.finalSize = float(finalSize)
38 self.finalBarLength = int(finalBarLength)
39 self.barChar = barChar
40 self.stream = stream
41 self.redrawYN = redrawYN
42 if self.stream not in [sys.stdout, sys.stderr]:
43 self.redrawYN = 0
44
46 self.size = 0.0
47 self.barLength = 0
48 self.barLengthPrinted = 0
49
51 """ Prints/reprints the prompt and current level of hashmarks.
52 Eg: ____________________
53 Processing: ###########
54 NOTE: The underscores only occur if you turn on contextYN.
55 """
56 if contextYN:
57 self.stream.write('%s%s\n' % (' ' * len(self.prompt), '_' * self.finalBarLength))
58 toPrint = self.prompt + self.barChar * self.barLength
59 if self.redrawYN:
60
61
62 self.stream.write('\b' * 80)
63 completeBar = len(self.prompt + self.endTag) + self.finalBarLength
64
65 self.stream.write(completeBar * ' ')
66
67 self.stream.write(completeBar * '\b')
68 self.stream.write(toPrint)
69 self.stream.flush()
70 self.barLengthPrinted = self.barLength
71
73 "visually updates the bar."
74 if self.redrawYN:
75 self.printAll(contextYN=0)
76 else:
77 self.stream.write(self.barChar * (self.barLength - self.barLengthPrinted))
78 self.stream.flush()
79 self.barLengthPrinted = self.barLength
80
82 """Completes the bar reguardless of current object status (and then
83 updates the object's status to complete)."""
84 self.complete()
85 self.printIncrement()
86 self.stream.write(self.endTag + '\n')
87 self.stream.flush()
88
90 "Update the status of the class to the newSize of the bar."
91 newSize = float(newSize)
92 if newSize >= self.finalSize:
93 newSize = self.finalSize
94 self.size = newSize
95 if self.finalSize == 0:
96 self.barLength = self.finalBarLength
97 else:
98 self.barLength = int((self.size * self.finalBarLength) / self.finalSize)
99 if self.barLength >= self.finalBarLength:
100 self.barLength = self.finalBarLength
101
102 - def addTo(self, additionalSize):
103 "Update the object's status to an additional bar size."
104 self.update(self.size + additionalSize)
105
107 self.update(self.finalSize)
108
109
110
111
112 if __name__ == '__main__':
113 print("An example:")
114 bar_length = 40
115 items = 200
116 pb = ProgressBar('standby: ', ' - all done!', items, bar_length, 'o')
117 pb.printAll(1)
118 for i in range(items):
119
120 pb.addTo(1)
121 time.sleep(0.005)
122 pb.printIncrement()
123 pb.printComplete()
124
125
126