misc.py (2053B)
1 """ 2 Bytes-to-human / human-to-bytes converter. 3 Based on: http://goo.gl/kTQMs 4 Working with Python 2.x and 3.x. 5 6 Author: Giampaolo Rodola' <g.rodola [AT] gmail [DOT] com> 7 License: MIT 8 """ 9 10 SYMBOLS = { 11 "customary": ("B", "K", "M", "G", "T", "P", "E", "Z", "Y"), 12 "customary_ext": ( 13 "byte", 14 "kilo", 15 "mega", 16 "giga", 17 "tera", 18 "peta", 19 "exa", 20 "zetta", 21 "iotta", 22 ), 23 "iec": ("Bi", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi"), 24 "iec_ext": ("byte", "kibi", "mebi", "gibi", "tebi", "pebi", "exbi", "zebi", "yobi"), 25 } 26 27 28 def bytes2human(n, format="%(value).1f %(symbol)s", symbols="customary"): 29 """ 30 Convert n bytes into a human readable string based on format. 31 symbols can be either "customary", "customary_ext", "iec" or "iec_ext", 32 see: http://goo.gl/kTQMs 33 34 >>> bytes2human(0) 35 '0.0 B' 36 >>> bytes2human(0.9) 37 '0.0 B' 38 >>> bytes2human(1) 39 '1.0 B' 40 >>> bytes2human(1.9) 41 '1.0 B' 42 >>> bytes2human(1024) 43 '1.0 K' 44 >>> bytes2human(1048576) 45 '1.0 M' 46 >>> bytes2human(1099511627776127398123789121) 47 '909.5 Y' 48 49 >>> bytes2human(9856, symbols="customary") 50 '9.6 K' 51 >>> bytes2human(9856, symbols="customary_ext") 52 '9.6 kilo' 53 >>> bytes2human(9856, symbols="iec") 54 '9.6 Ki' 55 >>> bytes2human(9856, symbols="iec_ext") 56 '9.6 kibi' 57 58 >>> bytes2human(10000, "%(value).1f %(symbol)s/sec") 59 '9.8 K/sec' 60 61 >>> # precision can be adjusted by playing with %f operator 62 >>> bytes2human(10000, format="%(value).5f %(symbol)s") 63 '9.76562 K' 64 """ 65 n = int(n) 66 if n < 0: 67 raise ValueError("n < 0") 68 symbols = SYMBOLS[symbols] 69 prefix = {} 70 for i, s in enumerate(symbols[1:]): 71 prefix[s] = 1 << (i + 1) * 10 72 for symbol in reversed(symbols[1:]): 73 if n >= prefix[symbol]: 74 value = float(n) / prefix[symbol] 75 return format % locals() 76 return format % dict(symbol=symbols[0], value=n)