2
|
1 |
# -*- coding: utf-8 -*-
|
|
2 |
#
|
|
3 |
# prettysize - print data sizes in format easily readable by humans
|
|
4 |
#
|
|
5 |
# Copyright (c) 2011 Radek Brich <radek.brich@devl.cz>
|
|
6 |
#
|
|
7 |
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
8 |
# of this software and associated documentation files (the "Software"), to deal
|
|
9 |
# in the Software without restriction, including without limitation the rights
|
|
10 |
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
11 |
# copies of the Software, and to permit persons to whom the Software is
|
|
12 |
# furnished to do so, subject to the following conditions:
|
|
13 |
#
|
|
14 |
# The above copyright notice and this permission notice shall be included in
|
|
15 |
# all copies or substantial portions of the Software.
|
|
16 |
#
|
|
17 |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
18 |
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
19 |
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
20 |
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
21 |
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
22 |
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
23 |
# THE SOFTWARE.
|
|
24 |
|
|
25 |
iec_prefixes = ('Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi')
|
|
26 |
si_prefixes = 'kMGTPEZY'
|
|
27 |
big_prefixes = 'KMGTPEZY'
|
|
28 |
|
|
29 |
|
|
30 |
def prettysize(num, base=1024, prefixes=si_prefixes, unit='B', sep=' '):
|
|
31 |
'''Convert data size in bytes to human readable aproximation.
|
|
32 |
|
|
33 |
Beware that default output is invalid by recent standardization.
|
|
34 |
Still, this form was in use for ages.
|
|
35 |
|
|
36 |
For standardized output, see prettysize_si and prettysize_iec.
|
|
37 |
|
|
38 |
'''
|
|
39 |
prefixes = list(prefixes)
|
|
40 |
prefix = ''
|
|
41 |
num = float(num)
|
|
42 |
while True:
|
|
43 |
if num < base:
|
|
44 |
# format number
|
|
45 |
out = '{:.2f}'.format(num)
|
|
46 |
# cut off trailing zeros
|
|
47 |
out = out.rstrip('0')
|
|
48 |
if out.endswith('.'):
|
|
49 |
out = out[:-1]
|
|
50 |
return out + sep + prefix + unit
|
|
51 |
num /= base
|
|
52 |
prefix = prefixes.pop(0)
|
|
53 |
|
|
54 |
raise OverflowError('Number is too large.')
|
|
55 |
|
|
56 |
|
|
57 |
def prettysize_si(num, **kw):
|
|
58 |
return prettysize(num, base=1000, **kw)
|
|
59 |
|
|
60 |
|
|
61 |
def prettysize_short(num):
|
|
62 |
return prettysize(num, unit='', sep='', prefixes=big_prefixes)
|
|
63 |
|
|
64 |
|
|
65 |
def prettysize_iec(num):
|
|
66 |
return prettysize(num, prefixes=iec_prefixes)
|
|
67 |
|