4 Bytes-to-human / human-to-bytes converter.
5 Based on: http://goo.gl/kTQMs
6 Working with Python 2.x and 3.x.
8 Author: Giampaolo Rodola' <g.rodola [AT] gmail [DOT] com>
11 http://code.activestate.com/recipes/578019-bytes-to-human-human-to-bytes-converter/
14 # see: http://goo.gl/kTQMs
16 'customary' : ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'),
17 'customary_ext' : ('byte', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa',
19 'iec' : ('Bi', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'),
20 'iec_ext' : ('byte', 'kibi', 'mebi', 'gibi', 'tebi', 'pebi', 'exbi',
24 def bytes2human(n
, format
='%(value).1f %(symbol)s', symbols
='customary'):
26 Convert n bytes into a human readable string based on format.
27 symbols can be either "customary", "customary_ext", "iec" or "iec_ext",
28 see: http://goo.gl/kTQMs
40 >>> bytes2human(1048576)
42 >>> bytes2human(1099511627776127398123789121)
45 >>> bytes2human(9856, symbols="customary")
47 >>> bytes2human(9856, symbols="customary_ext")
49 >>> bytes2human(9856, symbols="iec")
51 >>> bytes2human(9856, symbols="iec_ext")
54 >>> bytes2human(10000, "%(value).1f %(symbol)s/sec")
57 >>> # precision can be adjusted by playing with %f operator
58 >>> bytes2human(10000, format="%(value).5f %(symbol)s")
63 raise ValueError("n < 0")
64 symbols
= SYMBOLS
[symbols
]
66 for i
, s
in enumerate(symbols
[1:]):
67 prefix
[s
] = 1 << (i
+1)*10
68 for symbol
in reversed(symbols
[1:]):
69 if n
>= prefix
[symbol
]:
70 value
= float(n
) / prefix
[symbol
]
71 return format
% locals()
72 return format
% dict(symbol
=symbols
[0], value
=n
)
76 Attempts to guess the string format based on default symbols
77 set and return the corresponding bytes as an integer.
78 When unable to recognize the format ValueError is raised.
80 >>> human2bytes('0 B')
82 >>> human2bytes('1 K')
84 >>> human2bytes('1 M')
86 >>> human2bytes('1 Gi')
88 >>> human2bytes('1 tera')
91 >>> human2bytes('0.5kilo')
93 >>> human2bytes('0.1 byte')
95 >>> human2bytes('1 k') # k is an alias for K
97 >>> human2bytes('12 foo')
98 Traceback (most recent call last):
100 ValueError: can't interpret '12 foo'
104 while s
and s
[0:1].isdigit() or s
[0:1] == '.':
109 for name
, sset
in SYMBOLS
.items():
114 # treat 'k' as an alias for 'K' as per: http://goo.gl/kTQMs
115 sset
= SYMBOLS
['customary']
116 letter
= letter
.upper()
118 raise ValueError("can't interpret %r" % init
)
120 for i
, s
in enumerate(sset
[1:]):
121 prefix
[s
] = 1 << (i
+1)*10
122 return int(num
* prefix
[letter
])
125 if __name__
== "__main__":
129 print(bytes2human(sys
.argv
[1]))
130 print(human2bytes(sys
.argv
[2]))