Mine værktøjer
Du er her: Forside Python program eksempler. Sizes

Sizes

Tilbage

Hent filen

Licens GPL

Program to represent bytes in apropriate format.

#!/usr/bin/python
"""USAGE:sizes
Test formatBytes
GPL Licence. 
copyright Bauer Data ApS.
"""
# 
# see http://en.wikipedia.org/wiki/Bytes
radix ={
    "b" :1,       # bytes
    "kb":1024,    # Kilobyte
    "mb":1024**2, # Megabyte
    "gb":1024**3, # Gigabyte
    "tb":1024**4, # Terabyte
    "pb":1024**5, # Petabyte
    "eb":1024**6, # Exabyte
    "zb":1024**7, # Zettabyte
    "yb":1024**8, # Yottabyte
}

def formatBytes(value, suffix="b", decimals=1):
    """convert value with suffix to nice representation
     value      : is number to konvert
     suffix     : is valuer of values
     decimals   : is precission in output
    Examples
        formatBytes(1232345789452)              --> "1.1 tb"
        formatBytes(1232345789452,"mb")         --> "1.1 eb"
        formatBytes(1232345789452,decimals=3)   --> "1.121 tb"
    """
    # try to convert to nicest representation
    value *= float( radix[ suffix ] )
    if value < 1.0 :
        # fraction off bytes no possible
        return "0 b"

    # set prefferred format according to parameter decimals
    format="%%.%sf %%s" % (decimals)

    # if bytes larger then higest suffix safe the best fit value in less_res 
    less_res=value
    for (suffix, faktor) in radix.items():
        res = value/faktor
        if 1.0 <= res < 1024:
            if suffix=='b':
                # bytes dont come in float.
                format = "%s %s"
                res = int(res)
            return format % ( res, suffix )
        if less_res > res:
            less_res = res
            less_suffix=suffix

    else:
        # out off range use higst suffix to konvert :-)
        return format % ( less_res, less_suffix )


if __name__ == "__main__":

    print 'formatBytes(1232345789452)',
    print formatBytes(1232345789452)
    print 'formatBytes(1232345789452,"mb")',
    print formatBytes(1232345789452,"mb")
    print 'formatBytes(1232345789452,decimals=3)',
    print formatBytes(1232345789452,decimals=3)
    print formatBytes(0.664) # wrong fractions off bytes not possible
    print formatBytes(0.664,suffix="kb", decimals=3 )
    for suffix in radix.keys():
        for bytes in range (1024, 3000, 1300):
            print "formatBytes(%d,suffix=%s)\t= " % (bytes,suffix),
            print formatBytes(bytes,suffix=suffix)


« august 2018 »
søn man tir ons tor fre lør
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Chat Rooms
Dyrk motion

Trim ballerup

 

Powered by Plone, the Open Source Content Management System