Last active 1448080507

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

Revision 2c8a98628f33bcbab95cb33b8d2672385891674e

add_bytes.py Raw
1#!/usr/bin/env python3
2
3import argparse
4import sys
5
6SYMBOLS = ('kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zetta', 'iotta')
7
8def 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
37def 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
50def 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
59if __name__ == "__main__":
60 sys.exit(main())