diff options
author | Christian Poessinger <christian@poessinger.com> | 2021-10-25 21:02:27 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-10-25 21:02:27 +0200 |
commit | d0dc71d7d22be9336934e2f84873f7a052a7f824 (patch) | |
tree | ef57be8139edd86ab7f0c95df27145ed6ed40824 /python/vyos | |
parent | 316ae2ae4e7e06cbb3a59cc09002d1c48e3e5f07 (diff) | |
parent | 241a19943b7321aa1f2e2ece86b5ad68997390fe (diff) | |
download | vyos-1x-d0dc71d7d22be9336934e2f84873f7a052a7f824.tar.gz vyos-1x-d0dc71d7d22be9336934e2f84873f7a052a7f824.zip |
Merge pull request #1040 from dmbaturin/T3937
T3937: rewrite the "show system memory" script in Python
Diffstat (limited to 'python/vyos')
-rw-r--r-- | python/vyos/util.py | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/python/vyos/util.py b/python/vyos/util.py index 849b27d3b..2c4051a7a 100644 --- a/python/vyos/util.py +++ b/python/vyos/util.py @@ -489,6 +489,40 @@ def seconds_to_human(s, separator=""): return result +def bytes_to_human(bytes, initial_exponent=0): + """ 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. + """ + + from math import log2 + + bytes = bytes * (2**initial_exponent) + + # log2 is a float, while range checking requires an int + exponent = int(log2(bytes)) + + if exponent < 10: + value = bytes + suffix = "B" + elif exponent in range(10, 20): + value = bytes / 1024 + suffix = "KB" + elif exponent in range(20, 30): + value = bytes / 1024**2 + suffix = "MB" + elif exponent in range(30, 40): + value = bytes / 1024**3 + suffix = "GB" + else: + value = bytes / 1024**4 + suffix = "TB" + # Add a new case when the first machine with petabyte RAM + # hits the market. + + size_string = "{0:.2f} {1}".format(value, suffix) + return size_string def get_cfg_group_id(): from grp import getgrnam |