Mine værktøjer
Du er her: Forside diverse filer til download mm. bytes.py
Handlinger tilknyttet webside

bytes.py

af adminSidst opdateret 12/02 2008 12:10

Class Byte:

Klik her for at hente fil

Størrelse: 6.5 kB - Filtype text/python-source

Indhold af fil-indholdsobjekt

#!/usr/bin/python
"""USAGE:python bytes.py -v
Test Clas Byte: 
GPL Licence. 
copyright Bauer Data ApS.
""" 
# 
from types import *
class Byte:
    """represent byte value with suffix to nice representation
     value      : is number to konvert
     suffix     : is valuer of values
     decimals   : is precission in output. default 2
     out        : default "bi" alt "si". bi use 1024 as base and SI use 1000 as base
    Examples
    >>> A = Byte( 123456 )
    >>> B = Byte( 34234234 )
    >>> A
    120.56 kib
    >>> B
    32.65 mib
    >>> A + B
    32.77 mib
    >>> A + "12354 mb"
    11.51 gib
    >>> A - B
    -32.53 mib
    >>>
    """
    # see <a href="http://en.wikipedia.org/wiki/Bytes">http://en.wikipedia.org/wiki/Bytes</a>
    all_radix = {}
    radix = {
        "bi":{ # binary
            "b" :1,        # bytes
            "kib":1024,    # Kilobyte
            "mib":1024**2, # Megabyte
            "gib":1024**3, # Gigabyte
            "tib":1024**4, # Terabyte
            "pib":1024**5, # Petabyte
            "eib":1024**6, # Exabyte
            "zib":1024**7, # Zettabyte
            "yib":1024**8, # Yottabyte
        },
        "si":{ # usual repr.
            "b" :1,        # bytes
            "kb":1000,     # Kilobyte
            "mb":1000**2,  # Megabyte
            "gb":1000**3,  # Gigabyte
            "tb":1000**4,  # Terabyte
            "pb":1000**5,  # Petabyte
            "eb":1000**6,  # Exabyte
            "zb":1000**7,  # Zettabyte
            "yb":1000**8,  # Yottabyte
        }
    }
        
    def __init__( self, value, suffix="b", decimals=2, out="bi" ):
        """Initalize a Byte object
        >>> A = Byte( "1234567 mib" )
        >>> A
        1.18 tib
        >>> A = Byte( "1234567 mb" )
        >>> A
        1.12 tib
        >>> A = Byte( 1234567 )
        >>> A
        1.18 mib
        """
        self._set_radix()
        self.setDefaults( decimals=decimals, out=out )
        self.value = self.convertValue( value, suffix )

    def __radd__( self, other ):
        """Implement addition noninstance + Byte
        >>> A = Byte( 1234567 )
        >>> 1234567 + A
        2.35 mib
        >>> "123 mb" + A
        118.48 mib
        """
        if type( other ) is IntType or type( other ) is StringType or type( other ) is LongType :
            Other = Byte( other )
            return Byte( self.value + Other.value )
        return Byte( self.value + other.value )

    def __add__( self, other ):
        """Implement addition "Byte + noninstance" and "Byte + Byte"
        >>> A = Byte( 1234567 )
        >>> A + "12345"
        1.19 mib
        >>> A + "12345 mb"
        11.50 gib
        >>> B = Byte( 12345 )
        >>> A + B
        1.19 mib
        """
        if type(other) is IntType or type(other) is StringType or type(other) is LongType :
            Other = Byte( other )
            return Byte( self.value + Other.value )
        return Byte( self.value + other.value )

    def __sub__( self, other ):
        """Implement subtraction "Byte - noninstance" and "Byte - Byte"
        >>> A = Byte( 1234 )
        >>> A - "1233 b"
        1 b
        >>> B = Byte( 1233 )
        >>> A - B
        1 b
        """
        if type( other ) is IntType or type( other ) is StringType or type( other ) is LongType:
            Other = Byte( other )
            return Byte( self.value - Other.value )
        return Byte( self.value - other.value )

    def __rsub__( self, other ):
        """Implement subtraction noninstance - Byte
        >>> A = Byte( 1234 )
        >>> 1233 - A
        -1 b
        """
        if type( other ) is IntType or type( other ) is StringType or type( other ) is LongType:
            Other = Byte( other )
            return Byte( Other.value - self.value )
        return Byte(  other.value - self.value )

    def setDefaults( self, decimals=-1, out="" ):
        """set parameters for output format
        >>> A = Byte( 1234, "mb" )
        >>> A
        1.15 gib
        >>> A.setDefaults( out="si" )
        >>> A
        1.23 gb
        >>> A.setDefaults( decimals=1 )
        >>> A
        1.2 gb
        """
        if decimals > 0:
            self.decimals = decimals
        if out != "":
            self.out = out
        self.base = { "si":1000, "bi":1024 }[ self.out ]
        
    def convertValue( self, value, suffix="b" ) :
        """convert to bytes according to suffix
        >>> A = Byte( 1234, "mb" )
        >>> A
        1.15 gib
        >>> A = Byte( "1234  mb" )
        >>> A
        1.15 gib
        """
        try:
            value=float(value)
        except:
            ( value, suffix ) = value.split()
            value=float( value )
        suffix = suffix.lower()
        value *= float( Byte.all_radix[ suffix ] )
        if abs(value) < 1.0 and suffix == 'b':
            # fraction off bytes not possible
            value = 0 
        return value
        
    def _set_radix( self ):
        """Internal function to create a collection og suffix's
        >>> print "_set_radix"
        _set_radix
        """
        global all_radix
        if Byte.all_radix == {}:
            Byte.all_radix = Byte.radix[ "si" ].copy()
            Byte.all_radix.update( Byte.radix[ "bi" ] )
    

    def __repr__( self ):
        """print the byte nicely
        >>> A = Byte( 1, "kb" )
        >>> A
        1000 b
        >>> A = Byte( 1, "kib" )
        >>> A
        1.00 kib
        """
        outRadix = Byte.radix[ self.out ]
        # set prefferred format according to parameter decimals
        format = "%%.%sf %%s" % ( self.decimals )
        
        # if bytes larger then higest suffix
        # safe the best fit value in less_res 
        less_res = self.value
        less_suffix = "b"

        for ( suffix, faktor ) in Byte.radix[ self.out ].items():
            res = self.value/faktor
            if 1.0 <= abs( res ) < self.base:
                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:
            if suffix == 'b': return "0 b"
            # out off range use higst suffix to konvert :-)
            return format % ( less_res, less_suffix )

def _test():
    """Run doctest if run with option -v from commandline 
        python bytes.py -v
    """
    import doctest
    doctest.testmod()

if __name__ == "__main__":
    """Main only  executed from commandline"""
    A = Byte( 1234 )
    print 1233 - A
    _test()
« 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