From 336576bf58a48216d7c8719b97d1204468fda018 Mon Sep 17 00:00:00 2001 From: John Estabrook Date: Tue, 6 Dec 2022 09:06:47 -0600 Subject: vyos.util: T4770: add precision arg, fix typo in bytes_to_human This is useful in general, but we will add in this context to replace the use of 'bytes2HR' in show_openvpn.py with util.bytes_to_human, while maintaining compatability with original precision=1. --- python/vyos/util.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'python/vyos/util.py') diff --git a/python/vyos/util.py b/python/vyos/util.py index 9ebe69b6c..6a828c0ac 100644 --- a/python/vyos/util.py +++ b/python/vyos/util.py @@ -539,13 +539,16 @@ def seconds_to_human(s, separator=""): return result -def bytes_to_human(bytes, initial_exponent=0): +def bytes_to_human(bytes, initial_exponent=0, precision=2): """ Converts a value in bytes to a human-readable size string like 640 KB The initial_exponent parameter is the exponent of 2, e.g. 10 (1024) for kilobytes, 20 (1024 * 1024) for megabytes. """ + if bytes == 0: + return "0 B" + from math import log2 bytes = bytes * (2**initial_exponent) @@ -571,7 +574,7 @@ def bytes_to_human(bytes, initial_exponent=0): # Add a new case when the first machine with petabyte RAM # hits the market. - size_string = "{0:.2f} {1}".format(value, suffix) + size_string = "{0:.{1}f} {2}".format(value, precision, suffix) return size_string def human_to_bytes(value): -- cgit v1.2.3