Last active 1448080507

A script to sum byte values (e.g 7TB + 512GB = 7.5TB)

Steven Smith revised this gist 1448116506. Go to revision

1 file changed, 60 insertions

add_bytes.py(file created)

@@ -0,0 +1,60 @@
1 + #!/usr/bin/env python3
2 +
3 + import argparse
4 + import sys
5 +
6 + SYMBOLS = ('kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zetta', 'iotta')
7 +
8 + def get_bytes(data_queue):
9 + """Parses list of strings, ints or floats representing data amounts (e.g 1MB, 2mb, 3M) to a list of bytes. Parses all types listed in SYMBOLS.
10 +
11 + >>> add_bytes([500, "1.1mb", "23KB"])
12 + [500.0, 1153433.6, 23552.0]
13 + """
14 + output = []
15 + for item in data_queue:
16 + if type(item) in (int, float):
17 + output.append(float(item))
18 + continue
19 + if item[-1] in "bB": # we don't need to worry about bytes
20 + item = item[:-1]
21 + item = item.lower().strip() # for better matching
22 + try:
23 + output.append(float(item))
24 + continue
25 + except ValueError:
26 + pass
27 + power = 0 # so `if not power` works
28 + for x, symbol in enumerate(SYMBOLS):
29 + if symbol[0] in item:
30 + power = x + 1
31 + if not power: # string was not a match
32 + continue
33 + item = float("".join(c for c in item if c in "0123456789."))
34 + output.append(item * (1024 ** power))
35 + return output
36 +
37 + def parse_bytes(byte_list, precision=2):
38 + """ Parses list of ints or floats into summed 'human' amount rounded to 2dp.
39 +
40 + >>> parse_bytes([500, 1153433.6, 23552])
41 + "1.12MB"
42 + """
43 + total = sum(byte_list)
44 + i = -1
45 + while total > 1024:
46 + i += 1
47 + total = total / 1024
48 + return ("{:.%sf}{}B" % precision).format(total, SYMBOLS[i][0].upper())
49 +
50 + def main():
51 + parser = argparse.ArgumentParser()
52 + parser.add_argument("amounts", help="Array of data amounts to be processed", nargs="+")
53 + parser.add_argument("-p", "--precision", help="Number of decimal places in the output")
54 + args = parser.parse_args()
55 + byte_list = get_bytes(args.amounts)
56 + print(parse_bytes(byte_list, args.precision or 2))
57 + return 0
58 +
59 + if __name__ == "__main__":
60 + sys.exit(main())
Newer Older