Skip to content

Commit

Permalink
add readableSize function
Browse files Browse the repository at this point in the history
  • Loading branch information
xiaosu-zhu committed Jan 8, 2022
1 parent 4c711a5 commit 78fcccf
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion vlutils/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,37 @@
__all__ = [
"WaitingBar",
"LoggingDisabler",
"configLogging"
"configLogging",
"readableSize"
]


def readableSize(byteSize: int, floating: int = 2, binary: bool = True) -> str:
"""Convert bytes to human-readable string (like `-h` option in POSIX).
Args:
size (int): Total bytes.
floating (int, optional): Floating point length. Defaults to 2.
binary (bool, optional): Format as XB or XiB. Defaults to True.
Returns:
str: Human-readable string of size.
"""
size = float(byteSize)
unit = "B"
if binary:
for unit in ["B", "kiB", "MiB", "GiB", "TiB", "PiB"]:
if size < 1024.0 or unit == "PiB":
break
size /= 1024.0
return f"{size:.{floating}f}{unit}"
for unit in ["B", "kB", "MB", "GB", "TB", "PB"]:
if size < 1000.0 or unit == "PB":
break
size /= 1000.0
return f"{size:.{floating}f}{unit}"


class WaitingBar(DecoratorContextManager):
"""A CLI tool for printing waiting bar.
Expand Down

0 comments on commit 78fcccf

Please sign in to comment.