Play with human size some more
This commit is contained in:
parent
1136c64d49
commit
d726eb354d
@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
import sys
|
import sys
|
||||||
from contextlib import suppress
|
from contextlib import suppress
|
||||||
|
from typing import Tuple
|
||||||
|
|
||||||
from .operations import raw_mode, set_cursor_visible
|
from .operations import raw_mode, set_cursor_visible
|
||||||
|
|
||||||
@ -29,15 +30,18 @@ def get_key_press(allowed: str, default: str) -> str:
|
|||||||
return response
|
return response
|
||||||
|
|
||||||
|
|
||||||
def human_size(size: int, sep: str = ' ', max_num_of_decimals: int = 2) -> str:
|
def human_size(
|
||||||
|
size: int, sep: str = ' ',
|
||||||
|
max_num_of_decimals: int = 2,
|
||||||
|
unit_list: Tuple[str, ...] = ('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB')
|
||||||
|
) -> str:
|
||||||
""" Convert a size in bytes into a human readable form """
|
""" Convert a size in bytes into a human readable form """
|
||||||
divisor, suffix = 1, "B"
|
if size < 2:
|
||||||
for i, candidate in enumerate(('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB')):
|
return f'{size}{sep}{unit_list[0]}'
|
||||||
if size < (1 << ((i + 1) * 10)):
|
from math import log
|
||||||
divisor, suffix = (1 << (i * 10)), candidate
|
exponent = min(int(log(size, 1024)), len(unit_list) - 1)
|
||||||
break
|
ans = str(size / 1024**exponent)
|
||||||
ans = str(size / divisor)
|
|
||||||
pos = ans.find('.')
|
pos = ans.find('.')
|
||||||
if pos > -1:
|
if pos > -1:
|
||||||
ans = ans[:pos + max_num_of_decimals + 1]
|
ans = ans[:pos + max_num_of_decimals + 1]
|
||||||
return ans.rstrip('0').rstrip('.') + sep + suffix
|
return ans.rstrip('0').rstrip('.') + sep + unit_list[exponent]
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user