• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import math
2import os.path
3import sys
4import textwrap
5
6
7def format_duration(seconds):
8    ms = math.ceil(seconds * 1e3)
9    seconds, ms = divmod(ms, 1000)
10    minutes, seconds = divmod(seconds, 60)
11    hours, minutes = divmod(minutes, 60)
12
13    parts = []
14    if hours:
15        parts.append('%s hour' % hours)
16    if minutes:
17        parts.append('%s min' % minutes)
18    if seconds:
19        if parts:
20            # 2 min 1 sec
21            parts.append('%s sec' % seconds)
22        else:
23            # 1.0 sec
24            parts.append('%.1f sec' % (seconds + ms / 1000))
25    if not parts:
26        return '%s ms' % ms
27
28    parts = parts[:2]
29    return ' '.join(parts)
30
31
32def removepy(names):
33    if not names:
34        return
35    for idx, name in enumerate(names):
36        basename, ext = os.path.splitext(name)
37        if ext == '.py':
38            names[idx] = basename
39
40
41def count(n, word):
42    if n == 1:
43        return "%d %s" % (n, word)
44    else:
45        return "%d %ss" % (n, word)
46
47
48def printlist(x, width=70, indent=4, file=None):
49    """Print the elements of iterable x to stdout.
50
51    Optional arg width (default 70) is the maximum line length.
52    Optional arg indent (default 4) is the number of blanks with which to
53    begin each line.
54    """
55
56    blanks = ' ' * indent
57    # Print the sorted list: 'x' may be a '--random' list or a set()
58    print(textwrap.fill(' '.join(str(elt) for elt in sorted(x)), width,
59                        initial_indent=blanks, subsequent_indent=blanks),
60          file=file)
61
62
63def print_warning(msg):
64    print(f"Warning -- {msg}", file=sys.stderr, flush=True)
65