-
Notifications
You must be signed in to change notification settings - Fork 55
/
progressbar.py
2005 lines (1700 loc) · 76.1 KB
/
progressbar.py
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# pylint: disable=E1101
"""
Implement classes to represent the progress of a task.
Use the ProgressbarText class for tasks that do not use multiprocessing,
and the ProgressbarMultiProcessServer class for tasks using
multiprocessing.
Basically, the task code must call the "progress" function to update the
progress bar and pass a number equivalent to the increment in the progress
since the last call. The progressbar must know the maximum value equivalent
to all the progress, which is passed during object creator for
ProgressbarText class.
The ProgressbarMultiProcessServer is similar to ProgressbarText class,
accounts for the progress of multiple processes. For each process you need
to call the register_client_and_get_proxy_progressbar to get a proxy
progressbar, where the maximum value equivalent to all the progress that
will be performed by that process is passed in this proxy creation. Each
process then calls the progress method of the proxy progressbar.
Note that there is also a DummyProgressbar whose progress function does
nothing. This is useful when you want to give the user a choice to show or
not the progressbar such that the task code can always call the progress
method and you only change the progressbar object.
"""
import multiprocessing
import os
import sys
import time
import warnings
from typing import Any, List, Optional, Tuple, cast
from ..util.misc import pretty_time
try:
from IPython.display import display
from ipywidgets import FloatProgress, HBox, Label
_IPYTHON_AVAILABLE = True
except:
_IPYTHON_AVAILABLE = False
try:
# noinspection PyUnresolvedReferences
import zmq
except ImportError: # pragma: no cover
# We don't have a fallback for zmq, but only the
# ProgressbarZMQServer and ProgressbarZMQClient classes require it
pass
# Type used to store IP address and port number
ClientID = int
IPAddress = str
PortNumber = int
__all__ = [
'DummyProgressbar', 'ProgressBarBase', 'ProgressbarText',
'ProgressbarText2', 'ProgressbarText3', 'ProgressbarMultiProcessServer',
'ProgressbarMultiProcessClient', 'ProgressbarZMQServer',
'ProgressBarIPython', 'center_message', 'ProgressbarTextBase',
'ProgressbarDistributedServerBase', 'ProgressbarDistributedClientBase'
]
# If this function is ever used outside this file, then move it to the
# util.misc module.
def center_message(message: str,
length: int = 50,
fill_char: str = ' ',
left: str = '',
right: str = '') -> str:
"""
Return a string with `message` centralized and surrounded by
`fill_char`.
Parameters
----------
message: str
The message to be centered.
length : int
Total length of the centered message (original + any fill).
fill_char : str
Filling character.
left : str
Left part of the filling.
right : str
Right part of the filling.
Returns
-------
cent_message : str
The centralized message.
Examples
--------
>>> print(center_message("Hello World", 50, '-', 'Left', 'Right'))
Left-------------- Hello World --------------Right
"""
message_size = len(message)
left_size = len(left)
right_size = len(right)
fill_size = (length - (message_size + 2) - left_size - right_size)
left_fill_size = fill_size // 2 + (fill_size % 2)
right_fill_size = (fill_size // 2)
new_message = u"{0}{1} {2} {3}{4}".format(left, fill_char * left_fill_size,
message,
fill_char * right_fill_size,
right)
return new_message
# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# xxxxxxxxxxxxxxx DummyProgressbar - START xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# noinspection PyMethodMayBeStatic
class DummyProgressbar: # pragma: no cover
"""
Dummy progress bar that don't really do anything.
The idea is that it can be used in place of the :class:`ProgressbarText`
class, but without actually doing anything.
See also
--------
ProgressbarText
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
"""
Initializes the DummyProgressbar object.
This method accepts any argument without errors, but they won't
matter, since this class does nothing.
"""
def progress(self, count: int) -> None:
"""This `progress` method has the same signature from the one in the
:class:`ProgressbarText` class.
Nothing happens when this method is called.
Parameters
----------
count : int
Ignored
"""
# xxxxxxxxxx DummyProgressbar - END xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
class ProgressBarBase:
"""
Base class for all ProgressBar classes.
Parameters
----------
finalcount : int
The total amount that corresponds to 100%. Each time the progress
method is called with a number that number is added with the
current amount in the progressbar. When the amount becomes equal to
`finalcount` the bar will be 100% complete.
Notes
-----
Derived classes should implement :func:`_update_iteration` and
:func:`_display_current_progress`. Optionally derived class might also
implement :func:`_perform_initialization` and :func:`_perform_finalizations`
"""
def __init__(self, finalcount: int):
"""
Initializes the progressbar object.
Parameters
----------
finalcount : int
The total amount that corresponds to 100%. Each time the
progress method is called with a number that number is added
with the current amount in the progressbar. When the amount
becomes equal to `finalcount` the bar will be 100% complete.
"""
self.finalcount = finalcount
# This will be set to True after the `start` method is called to
# initialize the progressbar.
self._initialized = False
# This will be set to true when the progress reaches 100%. When
# this is True, any subsequent calls to the `progress` method will
# be ignored.
self._finalized = False
# This variable will store the time when the `start` method was
# called for the first time (either manually or in the `progress`
# method. It will be used for tracking the elapsed time.
self._start_time = 0.0
# This variable will store the time when the `stop` method was
# called for the first time (either manually or in the `progress`
# method. It will be used for tracking the elapsed time.
self._stop_time = 0.0
@property
def elapsed_time(self) -> str:
"""
Get method for the elapsed_time property.
Returns
-------
str
The elapsed time.
"""
elapsed_time = 0.0
if self._initialized is True:
if self._finalized is False:
elapsed_time = time.time() - self._start_time
else:
elapsed_time = self._stop_time - self._start_time
return pretty_time(elapsed_time)
def _count_to_percent(self, count: int) -> float:
"""
Convert a given count into the equivalent percentage.
Parameters
----------
count : int
The current count to be represented in the progressbar. The
progressbar represents this count as a percent value of
self.finalcount
Returns
-------
percentage : float
The percentage that `count` is of self.finalcount (between 0
and 100)
"""
percentage = (count / float(self.finalcount)) * 100.0
return percentage
def _perform_initialization(self) -> None:
"""
Perform any initializations for the progressbar.
This method should be implemented in sub-classes if any
initialization code should be run.
"""
def _perform_finalizations(self) -> None: # pragma: nocover
"""
Perform any finalization (cleanings) after the progressbar stops.
This method should be implemented in sub-classes if any
finalization code should be run.
"""
def start(self) -> None:
"""
Start the progressbar.
This method should be called just before the progressbar is used
for the first time. Among possible other things, it will store the
current time so that the elapsed time can be tracked.
"""
if self._initialized is False:
self._start_time = time.time()
self._perform_initialization()
self._initialized = True
def stop(self) -> None:
"""
Stop the progressbar.
This method is automatically called in the `progress` method when
the progress reaches 100%. If manually called, any subsequent call
to the `progress` method will be ignored.
"""
if self._finalized is False:
self._stop_time = time.time()
# When progress reaches 100% we set the internal variable
# to True so that any subsequent calls to the `progress`
# method will be ignored.
self._finalized = True
self._perform_finalizations()
# pylint:disable=R0201,W0613
def _update_iteration(self, count: int) -> None: # pragma: no cover
"""
Update the progressbar according with the new `count`.
Parameters
----------
count : int
The current count to be represented in the progressbar. The
progressbar represents this count as a percent value of
self.finalcount
"""
raise NotImplementedError("Implement this method in a subclass")
def _display_current_progress(self) -> None: # pragma: nocover
"""
Refresh the progress representation.
This method should be defined in a subclass.
"""
raise NotImplementedError("Implement this method in a subclass")
def progress(self, count: int) -> None:
"""
Updates the current progress.
Calling this function will update the the current progress.
Parameters
----------
count : int
The current count to be represented in the progressbar. The
progressbar represents this count as a percent value of
self.finalcount
Notes
-----
How the progressbar is actually represented depends on the
subclass. In the subclasses implement the `_update_iteration`
method to update the current representation of the progressbar and
the `_update_progress_display` to actually display the current
progress.
"""
if self._finalized is False:
# Start the progressbar. This only have an effect the first
# time it is called. It initializes the elapsed time tracking
# and call the _perform_initialization method to perform any
# initialization.
self.start()
# Sanity check. If count is greater then self.finalcount we set
# it to self.finalcount
if count > self.finalcount:
count = self.finalcount
# Update the progressbar representation. this is up to the
# subclass. Note that this method should not refresh the
# progressbar, which is left to the _display_current_progress
# method.
self._update_iteration(count)
# Refresh the progress representation.
self._display_current_progress()
# If count is equal to self.finalcount we have reached
# 100%. In that case, we also write a final newline
# character.
if count == self.finalcount:
self.stop()
# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# xxxxxxxxxxxxxxx ProgressbarTextBase - START xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# The code here and in some of the derived classes is inspired in the code
# located in
# http://nbviewer.ipython.org/url/github.com/ipython/ipython/raw/master/
# /examples/notebooks/Progress%20Bars.ipynb
#
# noinspection PyAbstractClass
class ProgressbarTextBase(ProgressBarBase): # pylint: disable=R0902,W0223
"""
Base class for Text progressbars.
Parameters
----------
finalcount : int
The total amount that corresponds to 100%. Each time the progress
method is called with a number that number is added with the
current amount in the progressbar. When the amount becomes equal to
`finalcount` the bar will be 100% complete.
progresschar : str, optional
The character used to represent progress.
message : str, optional
A message to be shown in the top of the progressbar.
output : File like object
Object with a 'write' method, which controls where the progress-bar
will be printed. By default sys.stdout is used, which means that
the progress will be printed in the standard output.
Notes
-----
Derived classes must implement at least `_update_iteration` and this
method should update the `prog_bar` member variable with the text
representation of the progress.
"""
def __init__(self,
finalcount: int,
progresschar: str = '*',
message: str = '',
output: Any = sys.stdout) -> None:
"""
Initializes the progressbar object.
Parameters
----------
finalcount : int
The total amount that corresponds to 100%. Each time the
progress method is called with a number that number is added
with the current amount in the progressbar. When the amount
becomes equal to `finalcount` the bar will be 100% complete.
progresschar : str, optional (default to '*')
The character used to represent progress.
message : str, optional
A message to be shown in the top of the progressbar.
output : File like object
Object with a 'write' method, which controls where the
progress-bar will be printed. By default sys.stdout is used,
which means that the progress will be printed in the standard
output.
"""
super(ProgressbarTextBase, self).__init__(finalcount)
# This will be updated with the progress and should contain the
# whole string representation of the progressbar.
self.prog_bar = "Progress Representation"
self.old_prog_bar = ""
# character used to represent progress
self.progresschar = progresschar
# If output points to a file (and not to stdout) and this is set to
# True, then the file will be erased after the progress finishes.
self.delete_progress_file_after_completion = False
# This should be a multiple of 10. The lower possible value is 40.
self._width = 50
# By default, self._output points to sys.stdout so I can use the
# write/flush methods to display the progress bar.
self._output = output
self._message = message # THIS WILL BE IGNORED
# If true, an empty line will be printed when the progress finishes
self._print_empty_line_at_the_end = True
def __del__(self) -> None:
"""
Delete the output file if there is any and
delete_progress_file_after_completion was set to True when the
progressbar object is deleted.
"""
# In case the progressbar object is deleted before the progress
# finishes the `stop` method will not be called and thus the output
# file (if there is any) would not be deleted even if
# delete_progress_file_after_completion was set to True. Therefore,
# we implement the __del__ method here to call the
# _maybe_delete_output_file method to do that.
self._maybe_delete_output_file()
# xxxxxxxxxx width property xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# Text progressbars have a width property indicating the width (in
# number of characters) of the full progress.
@property
def width(self) -> int:
"""Get method for the width property."""
return self._width
@width.setter
def width(self, value: int) -> None:
"""
Set method for the width property.
Parameters
----------
value : int
"""
# If value is lower than 40, the width will be set to 40.
# If value is not a multiple of 10, width will be set to the
# largest multiple of 10 which is lower then value.
if value < 40:
value = 40
self._width = value - (value % 10)
# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
def _get_percentage_representation(self,
percent: float,
central_message: str = '{percent}%',
left_side: str = '[',
right_side: str = ']') -> str:
"""
Get the percent representation as a string suitable to the text
progressbar.
Parameters
----------
percent : float
The percentage to be represented.
central_message : str
A message that will be in the middle of the percentage bar. If
there is the label '{percent}' in the central_message it will
be replaced by the percentage. If there is the label
'{elapsed_time}' in the central_message it will be replaced by
the elapsed time. Note that this message should be very small,
since it hides the progresschars.
left_side : str
The left side of the bar.
right_side : str
The right side of the bar.
Returns
-------
representation : str
A string with the representation of the percentage.
"""
# Remove any fractional part
percent_done = int(percent)
elapsed_time = self.elapsed_time
# Calculates how many characters are spent just for the sides.
sides_length = len(left_side) + len(right_side)
# The width should be large enough to contain both the left_side
# and right_side and still have (reasonable) enough space for the
# characters representing the progress.
assert self.width > sides_length + 20
# Space that will be used bu the characters representing the
# progress
all_full = self.width - sides_length
# Calculates how many characters will be used to represent the
# `percent_done` value
num_hashes = int((percent_done / 100.0) * all_full)
prog_bar = (left_side + self.progresschar * num_hashes + ' ' *
(all_full - num_hashes) + right_side)
# Replace the center of prog_bar with the message
central_message = central_message.format(percent=percent_done,
elapsed_time=elapsed_time)
pct_place = (len(prog_bar) // 2) - (len(str(central_message)) // 2)
prog_bar = prog_bar[0:pct_place] + central_message + prog_bar[
pct_place + len(central_message):]
return prog_bar
def _maybe_delete_output_file(self) -> None:
"""
Delete the output file (if there is any) when
delete_progress_file_after_completion is set to True.
"""
if self.delete_progress_file_after_completion is True:
# Try to get the file name associated with the output. If we
# can get an actual file and
# delete_progress_file_after_completion is set to True we will
# delete that file
try:
name = self._output.name
# We will only delete a file if the name does not point to
# stdout.
if name != '<stdout>':
try:
os.remove(name)
except OSError: # Pragma: no cover
pass
except AttributeError: # pragma: no cover
# If an attribute error was raised then the output is not a
# file like object and therefore we don't need to delete
# any file
pass
def _perform_finalizations(self) -> None:
"""
Perform any finalization (cleanings) after the progressbar stops.
"""
if self._print_empty_line_at_the_end is True:
# Print an empty line after the last iteration to be consistent
# with the ProgressbarText class
self._output.write(u"\n")
# Flush everything to guarantee that at this point everything
# is written to the output.
self._output.flush()
# This will only delete the output file if self._output
# actually points to a file and if
# self.delete_progress_file_after_completion is set to True
self._maybe_delete_output_file()
def _display_current_progress(self) -> None:
"""
Refresh the progress representation.
All text progressbars should implement the `_update_iteration` to
update the `prog_bar` member variable with the text representation
of the progressbar.
This method is responsible to sending this text representation to
the output.
"""
# We will only write the progress if it actually changed since
# the last time. This is specially useful when the output is a
# file and it will avoid writing many unnecessary equal lines to
# the file.
if self.old_prog_bar != self.prog_bar:
# Save the current prog_bar variable before it is updated in
# the _update_iteration method.
self.old_prog_bar = self.prog_bar
# We simple change the cursor to the beginning of the line and
# write the string representation of the prog_bar variable.
self._output.write(u'\r')
self._output.write(u'{0}'.format(self.prog_bar))
# Flush everything to guarantee that at this point
# everything is written to the output.
self._output.flush()
# The string representation of a text progressbar should display the
# whole progressbar
def __str__(self) -> str:
return str(self.prog_bar)
# xxxxxxxxxx ProgressbarTextBase - END xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# xxxxxxxxxxxxxxx ProgressbarText - START xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# http://
# code.activestate.com/recipes/299207-console-text-progress-indicator-class/
#
# CLASS NAME: ProgressbarText
#
# Original Author of the ProgressbarText class:
# Larry Bates (lbates@syscononline.com)
# Written: 12/09/2002
#
# Modified by Darlan Cavalcante Moreira in 10/18/2011
# Released under: GNU GENERAL PUBLIC LICENSE
class ProgressbarText(ProgressbarTextBase):
"""
Class that prints a representation of the current progress as text.
You can set the final count for the progressbar, the character that
will be printed to represent progress and a small message indicating
what the progress is related to.
In order to use this class, create an object outsize a loop and inside
the loop call the `progress` function with the number corresponding to
the progress (between 0 and finalcount). Each time the `progress`
function is called a number of characters will be printed to show the
progress. Note that the number of printed characters correspond is
equivalent to the progress minus what was already printed.
See also
--------
DummyProgressbar
Examples
--------
>> pb = ProgressbarText(100, 'o', "Hello Simulation")
>> pb.start()
---------------- Hello Simulation ---------------1
1 2 3 4 5 6 7 8 9 0
----0----0----0----0----0----0----0----0----0----0
>> pb.progress(20)
oooooooooo
>> pb.progress(40)
oooooooooooooooooooo
>> pb.progress(50)
ooooooooooooooooooooooooo
>> pb.progress(100)
oooooooooooooooooooooooooooooooooooooooooooooooooo
"""
def __init__(self,
finalcount: int,
progresschar: str = '*',
message: str = '',
output: Any = sys.stdout):
"""
Initializes the ProgressbarText object.
Parameters
----------
finalcount : int
The total amount that corresponds to 100%. Each time the
progress method is called with a number that number is added
with the current amount in the progressbar. When the amount
becomes equal to `finalcount` the bar will be 100% complete.
progresschar : str, optional (default to '*')
The character used to represent progress.
message : str, optional
A message to be shown in the top of the progressbar.
output : File like object
Object with a 'write' method, which controls where the
progress-bar will be printed. By default sys.stdout is used,
which means that the progress will be printed in the standard
output.
"""
ProgressbarTextBase.__init__(self, finalcount, progresschar, message,
output)
# stores how many characters where already printed in a previous
# call to the `progress` function
self.progresscharcount = 0
def __get_initialization_bartitle(self) -> str:
"""
Get the progressbar title.
The title is the first line of the progressbar initialization
message.
The bar title is something like the line below
------------------- % Progress ------------------1\n
when there is no message.
Returns
-------
str
The bar title.
Notes
-----
This method is only a helper method called in the
`_perform_initialization` method.
"""
if len(self._message) != 0:
message = self._message
else:
message = '% Progress'
bartitle = center_message(message, self.width + 1, '-', '', '1\n')
return bartitle
def __get_initialization_markers(self) -> Tuple[str, str]:
"""
The initialization markers 'mark' the current progress in the
progressbar that will appear below it.
Returns
-------
Tuple[str, str]
A tuple containing the 'two lines' with the progress
markers. That is, (marker_line1, marker_line2)
Notes
-----
This method is only a helper method called in the
`_perform_initialization` method.
"""
steps = self.width // 10 # This division must be exact
values1 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
values2 = ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0']
common = "{0}{1}\n"
line1sep = ' ' * (steps - 1)
line1 = common.format(line1sep, line1sep.join(values1))
line2sep = '-' * (steps - 1)
line2 = common.format(line2sep, line2sep.join(values2))
return line1, line2
def _perform_initialization(self) -> None:
bartitle = self.__get_initialization_bartitle()
marker_line1, marker_line2 = self.__get_initialization_markers()
self._output.write(bartitle)
self._output.write(marker_line1)
self._output.write(marker_line2)
def _update_iteration(self, count: int) -> None:
percentage = self._count_to_percent(count)
# Set the self.prog_bar variable simply as a string containing as
# many self.progresschar characters as necessary.
self.prog_bar = self._get_percentage_representation(percentage,
left_side='',
right_side='',
central_message='')
# xxxxxxxxxx ProgressbarText - END xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# xxxxxxxxxxxxxxx ProgressbarText2 - START xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
class ProgressbarText2(ProgressbarTextBase):
"""
Class that prints a representation of the current progress as text.
You can set the final count for the progressbar, the character that
will be printed to represent progress and a small message indicating
what the progress is related to.
In order to use this class, create an object outsize a loop and inside
the loop call the `progress` function with the number corresponding to
the progress (between 0 and finalcount). Each time the `progress`
function is called a number of characters will be printed to show the
progress. Note that the number of printed characters correspond is
equivalent to the progress minus what was already printed.
Parameters
----------
finalcount : int
The total amount that corresponds to 100%. Each time the progress
method is called with a number that number is added with the
current amount in the progressbar. When the amount becomes equal to
`finalcount` the bar will be 100% complete.
progresschar : str, optional (default to '*')
The character used to represent progress.
message : str, optional
A message to be shown in the right of the progressbar. If this
message contains "{elapsed_time}" it will be replaced by the
elapsed time.
output : File like object
Object with a 'write' method, which controls where the progress-bar
will be printed. By default sys.stdout is used, which means that
the progress will be printed in the standard output.
"""
def __init__(self,
finalcount: int,
progresschar: str = '*',
message: str = '',
output: Any = sys.stdout) -> None:
"""
Initializes the progressbar object.
Parameters
----------
finalcount : int
The total amount that corresponds to 100%. Each time the
progress method is called with a number that number is added
with the current amount in the progressbar. When the amount
becomes equal to `finalcount` the bar will be 100% complete.
progresschar : str, optional (default to '*')
The character used to represent progress.
message : str, optional
A message to be shown in the right of the progressbar. If this
message contains "{elapsed_time}" it will be replaced by the
elapsed time.
output : File like object
Object with a 'write' method, which controls where the
progress-bar will be printed. By default sys.stdout is used,
which means that the progress will be printed in the standard
output.
"""
ProgressbarTextBase.__init__(self, finalcount, progresschar, message,
output)
def _update_iteration(self, count: int) -> None:
"""
Update the self.prog_bar member variable according with the new
`count`.
Parameters
----------
count : int
The current count to be represented in the progressbar. The
progressbar represents this count as a percent value of
self.finalcount
"""
# Convert `count` to the equivalent percentage
percent_count = self._count_to_percent(count)
# Update the self.prog_bar variable with (only) the current
# percentage representation. The message is not included and will
# be appended after this.
self.prog_bar = self._get_percentage_representation(
percent_count,
central_message='{percent}%',
left_side='[',
right_side=']')
# Append the message to the self.prog_bar variable if there is one
# (or a default message if there is no message set)..
if len(self._message) != 0:
message = self._message.format(elapsed_time=self.elapsed_time)
self.prog_bar += " {0}".format(message)
else:
self.prog_bar += ' %d of %d complete' % (count, self.finalcount)
# xxxxxxxxxx ProgressbarText2 - END xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# xxxxxxxxxxxxxxx ProgressbarText3 - START xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
class ProgressbarText3(ProgressbarTextBase):
"""
Class that prints a representation of the current progress as text.
You can set the final count for the progressbar, the character that
will be printed to represent progress and a small message indicating
what the progress is related to.
In order to use this class, create an object outsize a loop and inside
the loop call the `progress` function with the number corresponding to
the progress (between 0 and finalcount). Each time the `progress`
function is called a number of characters will be printed to show the
progress. Note that the number of printed characters correspond is
equivalent to the progress minus what was already printed.
Parameters
----------
finalcount : int
The total amount that corresponds to 100%. Each time the progress
method is called with a number that number is added with the
current amount in the progressbar. When the amount becomes equal to
`finalcount` the bar will be 100% complete.
progresschar : str, optional (default to '*')
The character used to represent progress.
message : str, optional
A message to be shown in the progressbar.
output : File like object
Object with a 'write' method, which controls where the progress-bar
will be printed. By default sys.stdout is used, which means that
the progress will be printed in the standard output.
"""
def __init__(self,
finalcount: int,
progresschar: str = '*',
message: str = '',
output: Any = sys.stdout) -> None:
"""
Initializes the progressbar object.
Parameters
----------
finalcount : int
The total amount that corresponds to 100%. Each time the
progress method is called with a number that number is added
with the current amount in the progressbar. When the amount
becomes equal to `finalcount` the bar will be 100% complete.
progresschar : str, optional (default to '*')
The character used to represent progress.
message : str, optional
A message to be shown in the progressbar.
output : File like object
Object with a 'write' method, which controls where the
progress-bar will be printed. By default sys.stdout is used,
which means that the progress will be printed in the standard
output.
"""
ProgressbarTextBase.__init__(self, finalcount, progresschar, message,
output)
# The ProgressbarText3 class already prints an empty line after
# each update. Therefore, there is no need to print an empty line
# after all the progress has been finished.
self._print_empty_line_at_the_end = False
def _update_iteration(self, count: int) -> None:
"""
Update the self.prog_bar member variable according with the new
`count`.
Parameters
----------
count : int
The current count to be represented in the progressbar. The
progressbar represents this count as a percent value of
self.finalcount
"""
full_count = "{0}/{1}".format(count, self.finalcount)
if len(self._message) != 0:
self.prog_bar = center_message("{0} {1}".format(
self._message, full_count),
length=self.width,
fill_char=self.progresschar)
else:
self.prog_bar = center_message(full_count,
length=self.width,
fill_char=self.progresschar)
# xxxxxxxxxx ProgressbarText3 - END xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# xxxxxxxxxxxxxxx ProgressBarIPython xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
class ProgressBarIPython(ProgressBarBase): # pragma: no cover
"""
Progressbar for IPython notebooks.
The progressbar will be rendered using IPython widgets.
"""
def __init__(self,