Excellent, I've created some unittests and pushed to next, thanks! On Thu, Feb 28, 2013 at 3:18 AM, Yiqiao Pu <[email protected]> wrote: > Normalize a data size in one order of magnitude to another (MB to GB, > for example). In this function you can also change the factor as you > need, the default factor is 1024. > > changes from v1: > - rename the function and variables > - update the method for getting a fraction. > > Signed-off-by: Yiqiao Pu <[email protected]> > --- > virttest/utils_misc.py | 47 +++++++++++++++++++++++++++++++++++++++++++++++ > 1 files changed, 47 insertions(+), 0 deletions(-) > > diff --git a/virttest/utils_misc.py b/virttest/utils_misc.py > index d525a6c..2eba264 100644 > --- a/virttest/utils_misc.py > +++ b/virttest/utils_misc.py > @@ -1359,3 +1359,50 @@ def signal_program(program_name, sig=signal.SIGTERM, > pid_files_dir=None): > pid = get_pid_from_file(program_name, pid_files_dir) > if pid: > utils.signal_pid(pid, sig) > + > + > +def normalize_data_size(value_str, order_magnitude="M", factor="1024"): > + """ > + Normalize a data size in one order of magnitude to another (MB to GB, > + for example). > + > + @param value_str: a string include the data and unit > + @param order_magnitude: the magnitude order of result > + @param factor: the factor between two relative order of magnitude. > + Normally could be 1024 or 1000 > + """ > + def _get_magnitude_index(magnitude_list, magnitude_value): > + for i in magnitude_list: > + order_magnitude = re.findall("[\s\d](%s)" % i, > + str(magnitude_value), re.I) > + if order_magnitude: > + return magnitude_list.index(order_magnitude[0].upper()) > + return -1 > + > + magnitude_list = ['B', 'K', 'M', 'G', 'T'] > + try: > + data = float(re.findall("[\d\.]+",value_str)[0]) > + except IndexError: > + logging.error("Incorrect data size format. Please check %s" > + " has both data and unit." % value_str) > + return "" > + > + magnitude_index = _get_magnitude_index(magnitude_list, value_str) > + order_magnitude_index = _get_magnitude_index(magnitude_list, > + " %s" % order_magnitude) > + > + if magnitude_index < 0 or order_magnitude_index < 0: > + logging.error("Unknown input order of magnitude. Please check your" > + "value '%s' and desired order of magnitude" > + " '%s'." % (value_str, order_magnitude)) > + return "" > + > + if magnitude_index > order_magnitude_index: > + multiple = float(factor) > + else: > + multiple = float(factor) ** -1 > + > + for _ in range(abs(magnitude_index - order_magnitude_index)): > + data *= multiple > + > + return str(data) > -- > 1.7.7.6 > > _______________________________________________ > Virt-test-devel mailing list > [email protected] > https://www.redhat.com/mailman/listinfo/virt-test-devel
-- Lucas _______________________________________________ Virt-test-devel mailing list [email protected] https://www.redhat.com/mailman/listinfo/virt-test-devel
