1+ import time , sys
2+
3+ class ProgressBar :
4+ def __init__ (self ,
5+ pretext = "" ,
6+ progresschar = "-" ,
7+ loadingchars = r"\-/|" ,
8+ startendchar = "[]" ,
9+ barwidth = int (100 / 3 ),
10+ displaypercentage = False ,
11+ displaycount = False
12+ ):
13+ self .pretext = str (pretext )
14+ self .progresschar = str (progresschar )
15+ self .loadingchars = loadingchars
16+ self .startendchar = str (startendchar )
17+ self .barwidth = int (barwidth )
18+ self .displaypercentage = displaypercentage
19+ self .displaycount = displaycount
20+
21+ # loadingchars ideas
22+ # characters = "-/|\"
23+ # characters = ["-_="]
24+
25+ # Private
26+ self .loadingcharsindex = 0
27+ self .firstprint = True
28+
29+ # Function to link to a thread
30+ def inThread (self , number , total , updateperiod = 0.1 ):
31+ while (progressnumber .value != total ):
32+ self .print (False ,number .value ,total )
33+ time .sleep (float (updateperiod ))
34+ self .print (False ,total ,total )
35+
36+ def print (self ,number ,total ):
37+ barstring = ""
38+
39+ # No carriage return on first print
40+ if not self .firstprint :
41+ barstring += "\r "
42+ self .firstprint = False
43+
44+ # Pre progress bar
45+ if self .pretext :
46+ barstring += self .pretext
47+
48+ # Progress bar
49+ #Start char
50+ barstring += self .startendchar [0 ]
51+ #Current state of affairs
52+ sofarbar = int ( (number / total )* self .barwidth )
53+ remainingbar = self .barwidth - sofarbar
54+ #If loading chars, make sure there's space to print it
55+ if self .loadingchars != "" and sofarbar > 0 :
56+ sofarbar -= 1
57+ #Add progress chars
58+ barstring += sofarbar * self .progresschar
59+ #If loading chars, print loading chars and go to next one
60+ if self .loadingchars != "" :
61+ barstring += self .loadingchars [self .loadingcharsindex ])
62+ self .loadingcharsindex = (self .loadingcharsindex + 1 ) % len (self .loadingchars )
63+ #Add remaining gap
64+ barstring += remainingbar * " "
65+ #End char
66+ barstring += self .startendchar [0 ]
67+
68+ # Post progress bar
69+ if self .displaypercentage :
70+ barstring += " %d%%" % int (number * 100 / total )
71+ if self .displaycount :
72+ barstring += " (%d/%d)" % (number ,total )
73+
74+ # Print the bar out
75+ sys .stdout .write (barstring )
76+ sys .stdout .flush ()
0 commit comments