/
utils.py
3738 lines (2845 loc) · 106 KB
/
utils.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
"""
Core system and file I/O utilities.
Copyright 2017-2020, Voxel51, Inc.
voxel51.com
"""
# pragma pylint: disable=redefined-builtin
# pragma pylint: disable=unused-wildcard-import
# pragma pylint: disable=wildcard-import
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from builtins import *
from future.utils import iteritems, itervalues
import six
# pragma pylint: enable=redefined-builtin
# pragma pylint: enable=unused-wildcard-import
# pragma pylint: enable=wildcard-import
from collections import defaultdict, deque
from datetime import datetime
import dateutil.parser
import errno
import glob
import glob2
import hashlib
import importlib
import inspect
try:
# Although StringIO.StringIO's handling of unicode vs bytes is imperfect,
# we import it here for use when a text-buffer replacement for `print` in
# Python 2.X is required
from StringIO import StringIO as _StringIO # Python 2
except ImportError:
from io import StringIO as _StringIO # Python 3
import itertools as it
import logging
import math
import mimetypes
import numbers
import os
import packaging.version
import pytz
import random
import re
import shutil
import signal
import string
import subprocess
import sys
import tarfile
import tempfile
import timeit
import types
import zipfile as zf
import eta
import eta.constants as etac
logger = logging.getLogger(__name__)
def is_str(val):
"""Returns True/False whether the given value is a string."""
return isinstance(val, six.string_types)
def is_numeric(val):
"""Returns True/False whether the given value is numeric."""
return isinstance(val, numbers.Number)
def standarize_strs(arg):
"""Standardizes any strings in the given object by casting them via
`str()`. Dictionaries and lists are processed recursively.
Args:
arg: an object
Returns:
a copy (only if necessary) of the input object with any strings casted
via str()
"""
if isinstance(arg, dict):
return {
standarize_strs(k): standarize_strs(v) for k, v in iteritems(arg)
}
if isinstance(arg, list):
return [standarize_strs(e) for e in arg]
if is_str(arg):
return str(arg)
return arg
def summarize_long_str(s, max_len, mode="middle"):
"""Renders a shorter version of a long string (if necessary) to meet a
given length requirement by replacing part of the string with "..."
Args:
s: a string
max_len: the desired maximum length
mode: the summary mode, which controls which portion of long strings
are deleted. Supported values are ("first", "middle", "last"). The
default is "middle"
Returns:
the summarized string
"""
if len(s) <= max_len:
return s
_mode = mode.lower()
if _mode == "first":
return "... " + s[-(max_len - 4) :]
if _mode == "middle":
len1 = math.ceil(0.5 * (max_len - 5))
len2 = math.floor(0.5 * (max_len - 5))
return s[:len1] + " ... " + s[-len2:]
if _mode == "last":
return s[: (max_len - 4)] + " ..."
raise ValueError("Unsupported mode '%s'" % mode)
def get_localtime():
"""Gets the local time in "YYYY-MM-DD HH:MM:SS" format.
Returns:
"YYYY-MM-DD HH:MM:SS"
"""
return str(datetime.now().replace(microsecond=0))
def parse_isotime(isostr_or_none):
"""Parses the ISO time string into a datetime.
If the input string has a timezone ("Z" or "+HH:MM"), a timezone-aware
datetime will be returned. Otherwise, a naive datetime will be returned.
If the input is falsey, None is returned.
Args:
isostr_or_none: an ISO time string like "YYYY-MM-DD HH:MM:SS", or None
Returns:
a datetime, or None if the input was empty
"""
if not isostr_or_none:
return None
return dateutil.parser.parse(isostr_or_none)
def datetime_delta_seconds(time1, time2):
"""Computes the difference between the two datetimes, in seconds.
If one (but not both) of the datetimes are timezone-aware, the other
datetime is assumed to be expressed in UTC time.
Args:
time1: a datetime
time2: a datetime
Returns:
the time difference, in seconds
"""
try:
return (time2 - time1).total_seconds()
except (TypeError, ValueError):
time1 = add_utc_timezone_if_necessary(time1)
time2 = add_utc_timezone_if_necessary(time2)
return (time2 - time1).total_seconds()
def to_naive_local_datetime(dt):
"""Converts the datetime to a naive (no timezone) datetime with its time
expressed in the local timezone.
The conversion is performed as follows:
(1a) if the input datetime has no timezone, assume it is UTC
(1b) if the input datetime has a timezone, convert to UTC
(2) convert to local time
(3) remove the timezone info
Args:
dt: a datetime
Returns:
a naive datetime in local time
"""
dt = add_utc_timezone_if_necessary(dt)
return dt.astimezone().replace(tzinfo=None)
def to_naive_utc_datetime(dt):
"""Converts the datetime to a naive (no timezone) datetime with its time
expressed in UTC.
The conversion is performed as follows:
(1a) if the input datetime has no timezone, assume it is UTC
(1b) if the input datetime has a timezone, convert to UTC
(2) remove the timezone info
Args:
dt: a datetime
Returns:
a naive datetime in UTC
"""
dt = add_utc_timezone_if_necessary(dt)
return dt.astimezone(pytz.utc).replace(tzinfo=None)
def add_local_timezone_if_necessary(dt):
"""Makes the datetime timezone-aware, if necessary, by setting its timezone
to the local timezone.
Args:
dt: a datetime
Returns:
a timezone-aware datetime
"""
if dt.tzinfo is None:
dt = dt.astimezone() # empty ==> local timezone
return dt
def add_utc_timezone_if_necessary(dt):
"""Makes the datetime timezone-aware, if necessary, by setting its timezone
to UTC.
Args:
dt: a datetime
Returns:
a timezone-aware datetime
"""
if dt.tzinfo is None:
dt = dt.replace(tzinfo=pytz.utc)
return dt
def get_eta_rev():
"""Returns the hash of the last commit to the current ETA branch or "" if
something went wrong with git.
Returns:
the current ETA revision hash
"""
with WorkingDir(etac.ETA_DIR):
success, rev, _ = communicate(
["git", "rev-parse", "HEAD"], decode=True
)
return rev.strip() if success else ""
def has_gpu():
"""Determine if the current device has a GPU.
Returns:
True/False
"""
if sys.platform == "darwin":
# No GPU on mac
return False
try:
return "NVIDIA" in communicate(["lspci"], decode=True)[1]
except OSError:
# couldn't find lspci command...
return False
def get_int_pattern_with_capacity(max_number, zero_padded=True):
"""Gets an integer pattern like "%%03d" or "%%4d" with sufficient capacity
for the given number.
Args:
max_number: the maximum number you intend to pass to the pattern
zero_padded: whether to left-pad with zeros. By default, this is True
Returns:
an integer formatting pattern
"""
num_digits = max(1, math.ceil(math.log10(1 + max_number)))
if zero_padded:
return "%%0%dd" % num_digits
return "%%%dd" % num_digits
def fill_patterns(string, patterns):
"""Fills the patterns, if any, in the given string.
Args:
string: a string
patterns: a dictionary of key -> replace pairs
Returns:
a copy of string with any patterns replaced
"""
for patt, val in iteritems(patterns):
string = string.replace(patt, val)
return string
def fill_config_patterns(string):
"""Fills the patterns from ``eta.config.patterns``, if any, in the given
string.
Args:
string: a string
Returns:
a copy of string with any patterns replaced
"""
return fill_patterns(string, eta.config.patterns)
def parse_kvps(kvps_str):
"""Parses the comma-separated list of `key=value` pairs from the given
string.
Args:
kvps_str: a string of the form `"key1=val1,key2=val2,..."
Returns:
a dict of key-value pair strings
Raises:
ValueError: if the string was invalid
"""
kvps = {}
if kvps_str:
try:
for pair in kvps_str.split(","):
k, v = remove_escape_chars(pair, ",").strip().split("=")
kvps[k.strip()] = v.strip()
except ValueError:
raise ValueError("Invalid key-value pair string '%s'" % kvps_str)
return kvps
def parse_categorical_string(value, choices, ignore_case=True):
"""Parses a categorical string value, which must take a value from among
the given choices.
Args:
value: the string to parse
choices: either an iterable of possible values or an enum-like class
whose attributes define the possible values
ignore_case: whether to perform case insensitive matches. By default,
this is True
Returns:
the raw (untouched) value of the given field
Raises:
ValueError: if the value was not an allowed choice
"""
if inspect.isclass(choices):
choices = set(
v for k, v in iteritems(vars(choices)) if not k.startswith("_")
)
orig_value = value
orig_choices = choices
if ignore_case:
value = value.lower()
choices = set(c.lower() for c in choices)
if value not in choices:
raise ValueError(
"Unsupported value '%s'; choices are %s"
% (orig_value, orig_choices)
)
return orig_value
def parse_bool(val):
"""Parses the boolean value as per the table below.
| Input | Output |
| --------------------------------------------- | ------- |
| None, "None", "" | None |
| True, 1, "t", "T", "true", "True", "TrUe" | True |
| False, 0, "f", "F", "false", "False", "FaLsE" | False |
Args:
val: the value to parse
Returns:
True, False, or None
Raises:
ValueError: if the provided value is not a valid boolean representation
"""
if val is None:
return None
if isinstance(val, bool):
return val
if is_str(val):
val = val.lower()
if val in ("", "none"):
return None
if val in ("t", "true", "1"):
return True
if val in ("f", "false", "0"):
return False
if is_numeric(val):
if val == 0:
return False
if val == 1:
return True
raise ValueError("Failed to parse boolean from '%s'" % val)
class FunctionEnum(object):
"""Base class for enums that support string-based lookup into a set of
functions.
Subclasses must implement the `_FUNCTIONS_MAP` constant.
"""
#
# A dictionary mapping string values to functions
#
# Subclasses MUST implement this constant
#
_FUNCTIONS_MAP = {}
@classmethod
def get_function(cls, value):
"""Gets the function for the given value.
Args:
value: the FunctionEnum value
Returns:
the function
"""
cls.validate_value(value)
return cls._FUNCTIONS_MAP[value]
@classmethod
def is_valid_value(cls, value):
"""Determines whether the given value is valid.
Args:
value: the FunctionEnum value
Returns:
True/False
"""
try:
cls.validate_value(value)
return True
except ValueError:
return False
@classmethod
def validate_value(cls, value):
"""Validates that the given value is valid.
Args:
value: the FunctionEnum value
Raises:
ValueError: if the value is invalid
"""
if value not in cls._FUNCTIONS_MAP:
raise ValueError(
"'%s' is not a valid value for %s; supported values are %s"
% (value, get_class_name(cls), list(cls._FUNCTIONS_MAP))
)
def get_class_name(cls_or_obj):
"""Returns the fully-qualified class name for the given input, which can
be a class or class instance.
Args:
cls_or_obj: a class or class instance
Returns:
the fully-qualified class name string, such as
"eta.core.utils.ClassName"
"""
cls = cls_or_obj if inspect.isclass(cls_or_obj) else cls_or_obj.__class__
return cls_or_obj.__module__ + "." + cls.__name__
def get_function_name(fcn):
"""Returns the fully-qualified function name for the given function.
Args:
fcn: a function
Returns:
the fully-qualified function name string, such as
"eta.core.utils.function_name"
"""
return fcn.__module__ + "." + fcn.__name__
def get_class(class_name, module_name=None):
"""Returns the class specified by the given class string, loading the
parent module if necessary.
Args:
class_name: the "ClassName" or a fully-qualified class name like
"eta.core.utils.ClassName"
module_name: the fully-qualified module name like "eta.core.utils", or
None if class_name includes the module name. Set module_name to
__name__ to load a class from the calling module
Returns:
the class
Raises:
ImportError: if the class could not be imported
"""
if module_name is None:
try:
module_name, class_name = class_name.rsplit(".", 1)
except ValueError:
raise ImportError(
"Class name '%s' must be fully-qualified when no module "
"name is provided" % class_name
)
__import__(module_name) # does nothing if module is already imported
return getattr(sys.modules[module_name], class_name)
def get_function(function_name, module_name=None):
"""Returns the function specified by the given string.
Loads the parent module if necessary.
Args:
function_name: local function name by string fully-qualified name
like "eta.core.utils.get_function"
module_name: the fully-qualified module name like "eta.core.utils", or
None if function_name includes the module name. Set module_name to
__name__ to load a function from the calling module
Returns:
the function
Raises:
ImportError: if the function could not be imported
"""
return get_class(function_name, module_name=module_name)
def ensure_package(package_name, min_version=None, max_version=None):
"""Ensures that the given package is installed on the host machine.
Args:
package_name: the name of the package
min_version: an optional min version to enforce
max_version: an optional max version to enforce. If provided, the
package version must be strictly less than this version
Raises:
ImportError: if the package is not installed
"""
has_min_ver = min_version is not None
has_max_ver = max_version is not None
if has_min_ver:
min_version = packaging.version.parse(min_version)
if has_max_ver:
max_version = packaging.version.parse(max_version)
if has_min_ver:
if has_max_ver:
pkg_str = "%s<=%s<%s" % (min_version, package_name, max_version)
else:
pkg_str = "%s>=%s" % (package_name, min_version)
elif has_max_ver:
pkg_str = "%s<%s" % (package_name, max_version)
else:
pkg_str = package_name
try:
pkg = importlib.import_module(package_name)
except ImportError as e:
six.raise_from(
ImportError(
"The requested operation requires that '%s' is installed on "
"your machine" % pkg_str
),
e,
)
if has_min_ver or has_max_ver:
pkg_version = packaging.version.parse(pkg.__version__)
if (has_min_ver and pkg_version < min_version) or (
has_max_ver and pkg_version >= max_version
):
raise ImportError(
"The requested operation requires that '%s' is installed "
"on your machine; found '%s==%s'"
% (pkg_str, package_name, pkg_version)
)
def lazy_import(module_name, callback=None):
"""Returns a proxy module object that will lazily import the given module
the first time it is used.
Example usage::
import eta.core.utils as etau
# Lazy version of `import tensorflow as tf`
tf = etau.lazy_import("tensorflow")
# Other commands
# Now the module is loaded
tf.__version__
Args:
module_name: the fully-qualified module name to import
callback (None): a callback function to call before importing the
module
Returns:
a LazyModule
"""
return LazyModule(module_name, callback=callback)
def lazy_object(_callable):
"""Returns a proxy object that will lazily be created by calling the
provided callable the first time it is used.
Example usage::
#
# Calls `import_tf1()` to import the TF 1.X namespace the first time
# that `tf` is used
#
import eta.core.utils as etau
def import_tf1():
try:
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
except:
import tensorflow as tf
return tf
tf = etau.lazy_object(import_tf1)
Args:
_callable: a callable that returns the object when called
Returns:
a LazyObject
"""
return LazyObject(_callable)
class LazyModule(types.ModuleType):
"""Proxy module that lazily imports the underlying module the first time it
is actually used.
Args:
module_name: the fully-qualified module name to import
callback (None): a callback function to call before importing the
module
"""
def __init__(self, module_name, callback=None):
super(LazyModule, self).__init__(module_name)
self._module = None
self._callback = callback
def __getattr__(self, item):
if self._module is None:
self._import_module()
return getattr(self._module, item)
def __dir__(self):
if self._module is None:
self._import_module()
return dir(self._module)
def _import_module(self):
# Execute callback, if any
if self._callback is not None:
self._callback()
# Actually import the module
module = importlib.import_module(self.__name__)
self._module = module
# Update this object's dict so that attribute references are efficient
# (__getattr__ is only called on lookups that fail)
self.__dict__.update(module.__dict__)
class LazyObject(object):
"""Proxy object that lazily constructs the object the first time it is
actually used.
Args:
_callable: a callable that returns the object when called
"""
def __init__(self, _callable):
self._callable = _callable
self._obj = None
def __getattr__(self, attr):
if self._obj is None:
self._init()
return getattr(self._obj, attr)
def __dir__(self):
if self._obj is None:
self._init()
return dir(self._obj)
def _init(self):
# Actually construct the object
self._obj = self._callable()
# Update this object's dict so that attribute references are efficient
# (__getattr__ is only called on lookups that fail)
self.__dict__.update(self._obj.__dict__)
def query_yes_no(question, default=None):
"""Asks a yes/no question via the command-line and returns the answer.
This function is case insensitive and partial matches are allowed.
Args:
question: the question to ask
default: the default answer, which can be "yes", "no", or None (a
response is required). The default is None
Returns:
True/False whether the user replied "yes" or "no"
Raises:
ValueError: if the default value was invalid
"""
valid = {"y": True, "ye": True, "yes": True, "n": False, "no": False}
if default:
default = default.lower()
try:
prompt = " [Y/n] " if valid[default] else " [y/N] "
except KeyError:
raise ValueError("Invalid default value '%s'" % default)
else:
prompt = " [y/n] "
while True:
sys.stdout.write(question + prompt)
choice = six.moves.input().lower()
if default and not choice:
return valid[default]
if choice in valid:
return valid[choice]
print("Please respond with 'y[es]' or 'n[o]'")
class CaptureStdout(object):
"""Class for temporarily capturing stdout.
This class works by temporarily redirecting `sys.stdout` (and any stream
handlers of the root logger that are streaming to `sys.stdout`) to a
string buffer in between calls to `start()` and `stop()`.
Example (suppressing stdout)::
import eta.core.utils as etau
print("foo")
with etau.CaptureStdout():
print("Hello, world!")
print("bar")
Example (capturing stdout)::
import eta.core.utils as etau
cap = etau.CaptureStdout()
print("foo")
with cap:
print("Hello, world!")
print("bar")
print(cap.stdout)
"""
def __init__(self):
"""Creates a CaptureStdout instance."""
self._root_logger = logging.getLogger()
self._orig_stdout = None
self._cache_stdout = None
self._handler_inds = None
self._stdout_str = None
def __enter__(self):
self.start()
return self
def __exit__(self, *args):
self.stop()
@property
def is_capturing(self):
"""Whether stdout is currently being captured."""
return self._cache_stdout is not None
@property
def stdout(self):
"""The stdout string captured by the last use of this instance, or None
if no stdout has been captured.
"""
return self._stdout_str
def start(self):
"""Start capturing stdout."""
if self.is_capturing:
return
self._stdout_str = None
self._orig_stdout = sys.stdout
self._cache_stdout = _StringIO()
self._handler_inds = []
# Update root logger handlers, if necessary
for idx, handler in enumerate(self._root_logger.handlers):
if isinstance(handler, logging.StreamHandler):
if handler.stream == sys.stdout:
handler.stream = self._cache_stdout
self._handler_inds.append(idx)
# Update `sys.stdout`
sys.stdout.flush()
sys.stdout = self._cache_stdout
def stop(self):
"""Stop capturing stdout.
Returns:
a string containing the captured stdout
"""
if not self.is_capturing:
return ""
self._stdout_str = self._cache_stdout.getvalue()
self._cache_stdout.close()
self._cache_stdout = None
# Revert root logger handlers, if necessary
for idx in self._handler_inds:
self._root_logger.handlers[idx].stream = self._orig_stdout
self._handler_inds = None
# Revert `sys.stdout`
sys.stdout = self._orig_stdout
return self.stdout
class ProgressBar(object):
"""Class for printing a self-updating progress bar to stdout that tracks
the progress of an iterative process towards completion.
The simplest use of `ProgressBar` is to create an instance and then call it
(`__call__`) with an iterable argument, which will pass through elements of
the iterable when iterating over it, updating the progress bar each time an
element is emitted.
Alternatively, `ProgressBar`s can track the progress of a task towards a
total iteration count, where the current iteration is updated manually by
calling either `update()`, which will increment the iteration count by 1,
or via `set_iteration()`, which lets you manually specify the new iteration
status. By default, both methods will automatically redraw the bar. If
manual control over drawing is required, you can pass `draw=False` to
either method and then manually call `draw()` as desired.
It is highly recommended that you always invoke `ProgressBar`s using their
context manager interface via the `with` keyword, which will automatically
handle calling `start()` and `close()` to appropriately initialize and
finalize the task. Among other things, this ensures that stdout redirection
is appropriately ended when an exception is encountered.
When `start()` is called on the a `ProgressBar`, an internal timer is
started to track the elapsed time of the task. In addition, stdout is
automatically cached between calls to `draw()` and flushed each time
`draw()` is called, which means that you can freely mix `print` statements
into your task without interfering with the progress bar. When you are done
tracking the task, call the `close()` method to finalize the progress bar.
Both of these actions are automatically taken when the bar's context
manager interface is invoked or when it is called with an iterable.
If you want want to full manual control over the progress bar, call
`start()` to start the task, call `pause()` before any `print` statements,
and call `close()` when the task is finalized.
`ProgressBar`s can optionally be configured to print any of the following
statistics about the task:
- the elapsed time since the task was started
- the estimated time remaining until the task completes
- the current iteration rate of the task, in iterations per second
- customized status messages passed via the `suffix` argument
Example (wrapping an iterator)::
import time
import eta.core.utils as etau
with etau.ProgressBar() as pb:
for _ in pb(range(100)):
time.sleep(0.05)
Example (with print statements interleaved)::
import time
import eta.core.utils as etau
with etau.ProgressBar(100) as pb:
while not pb.complete:
if pb.iteration in {25, 50, 75}:
print("Progress = %.2f" % pb.progress)
time.sleep(0.05)
pb.update()
Example (tracking a bit total)::
import random
import time
import eta.core.utils as etau
with etau.ProgressBar(1024 ** 2, use_bits=True) as pb:
while not pb.complete:
pb.update(random.randint(1, 10 * 1024))
time.sleep(0.05)
"""
def __init__(
self,
total=None,
show_percentage=True,
show_iteration=True,
show_elapsed_time=True,
show_remaining_time=True,
show_iter_rate=True,
iters_str="it",
start_msg=None,
complete_msg=None,
use_bits=False,