Exemplo n.º 1
0
def convert_cfunits(from_value,
                    from_unit,
                    wanted_unit=None,
                    suppress_unit=False):
    """ Use the cfunits-python package to handle the interaction with udunits2 """
    try:
        from cfunits import Units
    except ImportError:
        raise Exception("cfunits option relies on cfunits-python package")
    ZERO = False
    if float(from_value) == 0:
        # special Zero handling
        if from_unit != '1':
            warnings.warn("""Found a 0, udunits2 breaks,
            so we are assuming that this is not a non-zero based conversion like temperature"""
                          )
        ZERO = True
        from_value = 1.
    if wanted_unit:
        return Units.conform(from_value, Units(from_unit), Units(wanted_unit))
    out = Units(" ".join((str(from_value), from_unit))).format()
    split_out = out.split(' ')
    if len(split_out) == 1:
        out = (1., split_out[0])
    else:
        if ZERO:
            out = (0.0, split_out[1])
        else:
            out = (float(split_out[0]), split_out[1])

    if suppress_unit:
        return out[0]
    return out