humanfriendly
humanfriendly is a Python library that provides user-friendly output for text interfaces, including parsing and formatting numbers, file sizes, pathnames, and timespans. It also offers utilities for terminal interaction like text styling and prompting. The current version is 10.0, released in September 2021, with a release cadence that has included several minor and major updates in recent years and ongoing maintenance for Python compatibility on various platforms.
Warnings
- deprecated Many functions previously available directly from the top-level `humanfriendly` package are now aliases to functions in submodules (e.g., `humanfriendly.prompts.prompt_for_input`). Accessing these aliases will trigger a `DeprecationWarning`.
- breaking The internal `time_units` data structure was changed. Although not formally part of the documented API, this constitutes a technically backwards incompatible change if users were directly importing or relying on this internal variable.
- gotcha The default behavior for `format_size()` and `parse_size()` changed from using binary multiples (base-2, e.g., KiB) to decimal multiples (base-10, e.g., KB) in an earlier major version. Users expecting binary representation by default may get unexpected results.
- gotcha On Windows, advanced terminal styling and ANSI escape sequence features (like colors and spinners) might not work correctly without the `colorama` package, especially on older Windows versions. While Windows 10+ has native support, `colorama` provides broader compatibility.
Install
-
pip install humanfriendly
Imports
- format_size
from humanfriendly import format_size
- parse_size
from humanfriendly import parse_size
- prompt_for_input
from humanfriendly.prompts import prompt_for_input
- format_timespan
from humanfriendly import format_timespan
Quickstart
import os
from humanfriendly import format_size, parse_size
from humanfriendly.prompts import prompt_for_input
# Example of parsing and formatting file sizes
user_input = prompt_for_input("Enter a human-readable file size (e.g., 16GB, 5MB): ")
num_bytes = parse_size(user_input)
print(f"Parsed bytes: {num_bytes}")
print(f"Formatted (decimal): {format_size(num_bytes)}")
print(f"Formatted (binary): {format_size(num_bytes, binary=True)}")
# Example of formatting a timespan
from humanfriendly import format_timespan
seconds = 3665 # 1 hour, 1 minute, 5 seconds
print(f"Formatted timespan: {format_timespan(seconds)}")
# To demonstrate CLI features like spinners (requires running in terminal):
# import subprocess
# subprocess.run(['humanfriendly', '--demo'])