### Demonstrate ANSI Color Support with Humanfriendly CLI Source: https://context7.com/xolox/python-humanfriendly/llms.txt Provides an example of invoking the humanfriendly CLI's demo mode, which showcases its support for ANSI color codes in terminal output. ```bash # Demonstrate ANSI color support $ humanfriendly --demo ``` -------------------------------- ### Verify distutils.spawn availability via terminal Source: https://github.com/xolox/python-humanfriendly/blob/master/CHANGELOG.rst A console command used to verify the presence of the distutils.spawn module across multiple installed Python versions on a Linux system. This helps diagnose ModuleNotFoundError issues in environments where standard library components might be missing or customized. ```console $ ls -l /usr/lib/python*/distutils/spawn.py ``` -------------------------------- ### Reformat Usage Messages for Sphinx Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md The `usage_message_callback` function is designed to integrate with Sphinx's `autodoc-process-docstring` event. It reformats module docstrings using `render_usage` to ensure human-readable usage messages are not mangled by Sphinx. This function should typically be enabled via `enable_usage_formatting` and not called directly. It only processes module docstrings starting with `USAGE_MARKER`. ```python def usage_message_callback(app, what, name, obj, options, lines): """Reformat human friendly usage messages to [reStructuredText](https://en.wikipedia.org/wiki/ReStructuredText).""" # Implementation details would go here, likely involving calls to render_usage pass ``` -------------------------------- ### humanfriendly.prompts.prepare_friendly_prompts Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Enables user-friendly interactive prompts by configuring the readline module. ```APIDOC ## humanfriendly.prompts.prepare_friendly_prompts ### Description Make interactive prompts more user friendly by configuring the readline module. ### Method Function ### Endpoint N/A (Python function) ### Parameters None ### Request Example ```python import humanfriendly.prompts humanfriendly.prompts.prepare_friendly_prompts() ``` ### Response #### Success Response (200) N/A (This function modifies global state for prompts) #### Response Example N/A ``` -------------------------------- ### Timer Properties Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Access properties of the Timer class to get elapsed time and formatted string representations. ```APIDOC ## Timer Properties ### Description Access properties of the Timer class to retrieve information about the elapsed time. ### Method N/A (Properties of the Timer class) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python from humanfriendly import Timer timer = Timer() # ... some operations ... elapsed = timer.elapsed_time rounded_time = timer.rounded string_representation = str(timer) ``` ### Response #### Success Response (200) - **elapsed_time** (float) - The number of seconds counted so far. - **rounded** (str) - Human readable timespan rounded to seconds. #### Response Example ```json { "elapsed_time": 5.123, "rounded": "5 seconds" } ``` ``` -------------------------------- ### Create a basic terminal spinner in Python Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Demonstrates how to initialize and advance a simple terminal spinner using a context manager. The spinner provides visual feedback during iterative operations. ```python import itertools import time from humanfriendly import Spinner with Spinner(label="Downloading") as spinner: for i in itertools.count(): # Do something useful here. time.sleep(0.1) # Advance the spinner. spinner.step() ``` -------------------------------- ### Manage Temporary Directories with Python Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Demonstrates the use of the TemporaryDirectory context manager to create and automatically clean up temporary file system directories during test execution. ```python import os from humanfriendly.testing import TemporaryDirectory with TemporaryDirectory() as directory: # Do something useful here. assert os.path.isdir(directory) ``` -------------------------------- ### Create a terminal spinner with progress tracking in Python Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Displays a spinner that tracks completion percentage. The step method is updated with the current progress value to show the user how much of the task is finished. ```python import itertools import random import time from humanfriendly import Spinner, Timer with Spinner(label="Downloading", total=100) as spinner: progress = 0 while progress < 100: # Do something useful here. time.sleep(0.1) # Advance the spinner. spinner.step(progress) # Determine the new progress value. progress += random.random() * 5 ``` -------------------------------- ### Parse and Convert Dates with humanfriendly Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Demonstrates parsing date strings into tuples and converting them into Unix timestamps or datetime objects. It also shows how to combine these with format_timespan for human-readable duration calculations. ```python from humanfriendly import parse_date, format_timespan from time import mktime, time from datetime import datetime # Basic parsing print(parse_date('2013-06-17 02:47:42')) # Convert to Unix time unix_time = mktime(parse_date('2013-06-17 02:47:42') + (-1, -1, -1)) # Convert to datetime object dt = datetime(*parse_date('2013-06-17 02:47:42')) # Calculate timespan seconds_since_then = time() - unix_time print(format_timespan(seconds_since_then)) ``` -------------------------------- ### Parse and Format File Sizes in Python Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/readme.md Demonstrates parsing human-readable file sizes into bytes and formatting byte counts back into human-readable strings using the `humanfriendly` package. It shows both standard SI formatting and binary (GiB) formatting. ```python >>> from humanfriendly import format_size, parse_size >>> from humanfriendly.prompts import prompt_for_input >>> user_input = prompt_for_input("Enter a readable file size: ") Enter a readable file size: 16G >>> num_bytes = parse_size(user_input) >>> print(num_bytes) 16000000000 >>> print("You entered:", format_size(num_bytes)) You entered: 16 GB >>> print("You entered:", format_size(num_bytes, binary=True)) You entered: 14.9 GiB ``` -------------------------------- ### Convert HTML to ANSI using humanfriendly Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Demonstrates the use of the html_to_ansi utility function to render formatted text and colored output in a terminal environment. ```python from humanfriendly.text import dedent from humanfriendly.terminal import html_to_ansi print(html_to_ansi(dedent(''' Hello world! Is this thing on? I guess I can underline or strike-through text? And what about color? '''))) rainbow_colors = [ '#FF0000', '#E2571E', '#FF7F00', '#FFFF00', '#00FF00', '#96BF33', '#0000FF', '#4B0082', '#8B00FF', '#FFFFFF', ] html_rainbow = "".join('o' % c for c in rainbow_colors) print(html_to_ansi("Let's try a rainbow: %s" % html_rainbow)) ``` -------------------------------- ### Run Commands with Spinner and Timer using Humanfriendly CLI Source: https://context7.com/xolox/python-humanfriendly/llms.txt Demonstrates how to execute a command using the humanfriendly CLI, which displays a spinner during execution and times the operation. ```bash # Run a command with spinner and timer $ humanfriendly --run-command sleep 5 ``` -------------------------------- ### humanfriendly.prompts.prepare_prompt_text Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Wraps prompt text in ANSI escape sequences for enhanced terminal display, with options for readline hints. ```APIDOC ## humanfriendly.prompts.prepare_prompt_text ### Description Wrap a text to be rendered as an interactive prompt in ANSI escape sequences. ### Method Function ### Endpoint N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import humanfriendly.prompts formatted_text = humanfriendly.prompts.prepare_prompt_text("Enter your name: ") print(formatted_text) ``` ### Response #### Success Response (200) - **prompt_text** (str) - The text to render on the prompt. - **options** (dict) - Any keyword arguments passed to `ansi_wrap()`. - **Returns** (str) - The resulting prompt text, potentially with ANSI escape sequences. #### Response Example ```json "\u001b[32mEnter your name: \u001b[0m" ``` ``` -------------------------------- ### Parse and format file sizes in Python Source: https://github.com/xolox/python-humanfriendly/blob/master/README.rst Demonstrates how to convert human-readable size strings into byte integers using parse_size, and how to format byte integers back into human-readable strings using format_size with optional binary unit support. ```python from humanfriendly import format_size, parse_size from humanfriendly.prompts import prompt_for_input user_input = prompt_for_input("Enter a readable file size: ") num_bytes = parse_size(user_input) print(num_bytes) print("You entered:", format_size(num_bytes)) print("You entered:", format_size(num_bytes, binary=True)) ``` -------------------------------- ### Execute terminal demonstration Source: https://github.com/xolox/python-humanfriendly/blob/master/README.rst Runs the built-in demonstration of terminal text styles and ANSI escape sequences provided by the humanfriendly CLI. ```bash humanfriendly --demo ``` -------------------------------- ### Compatibility Helpers Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Utilities to ensure code compatibility between Python 2 and Python 3 environments. ```APIDOC ## [FUNCTION] humanfriendly.compat.coerce_string ### Description Coerces any provided value into a Unicode string, handling differences between Python 2 (unicode) and Python 3 (str). ### Parameters - **value** (any) - Required - The value to be converted to a string. ### Response - **result** (string) - The string representation of the input value. ### Response Example "example_string" ``` -------------------------------- ### format_path Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Shortens an absolute pathname by abbreviating the user's home directory. ```APIDOC ## FUNCTION humanfriendly.format_path ### Description Shorten a pathname to make it more human friendly by replacing the home directory with '~'. ### Parameters #### Arguments - **pathname** (string) - Required - The absolute path to shorten. ### Response - **Returns** (string) - The abbreviated path. ### Example ```python format_path('/home/user/.vimrc') # '~/.vimrc' ``` ``` -------------------------------- ### Prompt User for Confirmation - Python Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Asks the user a yes/no question for confirmation. It supports a default value and controls input formatting with the `padding` parameter. Returns `True` for 'yes', `False` for 'no', or the `default` value if input is ambiguous or unavailable. Raises exceptions from `retry_limit` and `prompt_for_input`. ```python from humanfriendly.prompts import prompt_for_confirmation # Example with a question and default set to False confirmation = prompt_for_confirmation("Do you want to proceed?", default=False) print(f"Confirmation result: {confirmation}") # Example with a question and no default confirmation_no_default = prompt_for_confirmation("Are you sure about this action?") print(f"Confirmation result (no default): {confirmation_no_default}") # Example with padding disabled confirmation_no_padding = prompt_for_confirmation("Continue?", padding=False) print(f"Confirmation result (no padding): {confirmation_no_padding}") ``` -------------------------------- ### CLI Utilities Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Functions for formatting data for human readability and executing commands via the CLI. ```APIDOC ## [FUNCTION] humanfriendly.cli.print_formatted_size ### Description Prints a human-readable data size string to standard output. ### Parameters - **value** (int/float) - Required - The size in bytes to format. - **binary** (bool) - Optional - Whether to use binary prefixes (KiB, MiB) instead of decimal. ### Response Example "1.23 MiB" ``` -------------------------------- ### Format Table Data from Stdin with Humanfriendly CLI Source: https://context7.com/xolox/python-humanfriendly/llms.txt Illustrates how to pipe data into the humanfriendly CLI to format it as a table, including headers and aligned columns. ```bash # Format table from stdin $ echo -e "Name Age\nAlice 30\nBob 25" | humanfriendly --format-table ``` -------------------------------- ### Run Humanfriendly Terminal Demo Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/readme.md Executes the command-line interface demo for the `humanfriendly` package, showcasing its terminal interaction features and support for ANSI escape sequences. ```shell $ humanfriendly --demo ``` -------------------------------- ### render_usage Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Reformats a plain text command-line usage message into reStructuredText format. ```APIDOC ## FUNCTION humanfriendly.usage.render_usage ### Description Converts a plain text usage message into a reStructuredText-formatted string suitable for documentation. ### Parameters #### Arguments - **text** (string) - Required - The plain text usage message. ### Response #### Success Response (200) - **string** - The reformatted usage message in reStructuredText. ``` -------------------------------- ### Handle Parsing Exceptions in humanfriendly Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Demonstrates how the library raises specific exceptions when input strings fail to parse into dates, lengths, sizes, or timespans. ```pycon >>> from humanfriendly import parse_date, parse_length, parse_size, parse_timespan >>> parse_date('2013-06-XY') >>> parse_length('5 Z') >>> parse_size('5 Z') >>> parse_timespan('1 age') ``` -------------------------------- ### Prompt user for input and choices Source: https://context7.com/xolox/python-humanfriendly/llms.txt Provides functions to handle user interaction via the command line, including selection menus, yes/no confirmations, and free-form text input. ```python from humanfriendly.prompts import prompt_for_choice, prompt_for_confirmation, prompt_for_input # Choice prompt options = ['Option A', 'Option B', 'Option C'] selected = prompt_for_choice(options, default='Option A') # Confirmation prompt if prompt_for_confirmation("Are you sure you want to continue?"): print("Proceeding...") # Text input name = prompt_for_input("What is your name?", default="Guest") ``` -------------------------------- ### Use Linux Manual Page Role in Sphinx Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Demonstrates the use of the :man: role in reStructuredText to generate hyperlinks to Debian Linux manual pages. ```rst See the :man:`python` documentation. ``` -------------------------------- ### Parse Plain Text Usage Message (Python) Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Parses a plain text usage message by inferring its structure. It assumes specific formats for the 'Usage:' line, 'Supported options:' section, and option documentation. It returns a tuple containing introduction paragraphs and a list of options with their descriptions. ```python from humanfriendly.usage import parse_usage usage_text = """ Usage: my_program [OPTIONS] ARGUMENT This is a sample program. Supported options: -h, --help Show this help message and exit. -v, --verbose Enable verbose output. """ introduction, options = parse_usage(usage_text) ``` -------------------------------- ### Use PyPI Package Role in Sphinx Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Demonstrates the use of the :pypi: role in reStructuredText to generate hyperlinks to packages on the Python Package Index. ```rst See the :pypi:`humanfriendly` package. ``` -------------------------------- ### Parse Human-Readable Sizes with Humanfriendly CLI Source: https://context7.com/xolox/python-humanfriendly/llms.txt Illustrates how to use the humanfriendly CLI to parse human-readable size strings (e.g., '1.5 GB') back into their raw byte values. ```bash # Parse sizes $ humanfriendly --parse-size="1.5 GB" 1500000000 ``` -------------------------------- ### Configure terminal defaults and patterns Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Default configuration settings for terminal dimensions and encoding, along with a compiled regular expression for identifying and cleaning terminal control characters. ```python import re CLEAN_OUTPUT_PATTERN = re.compile('(\r|\n|\x08|\x1b\\[K)') DEFAULT_COLUMNS = 80 DEFAULT_ENCODING = 'UTF-8' DEFAULT_LINES = 25 HIGHLIGHT_COLOR = 'green' ``` -------------------------------- ### Create a terminal spinner with elapsed time in Python Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Shows how to integrate a Timer object with a Spinner to display the elapsed duration of a task. This is useful for tracking how long a process has been running. ```python import itertools import time from humanfriendly import Spinner, Timer with Spinner(label="Downloading", timer=Timer()) as spinner: for i in itertools.count(): # Do something useful here. time.sleep(0.1) # Advance the spinner. spinner.step() ``` -------------------------------- ### Convert HTML to ANSI with humanfriendly Source: https://context7.com/xolox/python-humanfriendly/llms.txt Demonstrates the use of the html_to_ansi function to convert HTML-formatted strings into ANSI-colored terminal output. ```python from humanfriendly.terminal import html_to_ansi html_code = '
def hello(): print("world")
' print(html_to_ansi(html_code)) ``` -------------------------------- ### Prompt User for Choice - Python Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Prompts the user to select an option from a list of choices. It handles cases with no options, a single option, and user input validation. The `padding` parameter controls whitespace. Raises `ValueError` if `choices` is empty. ```python from humanfriendly.prompts import prompt_for_choice # Example with choices and default choices = ['option1', 'option2', 'option3'] selected_choice = prompt_for_choice(choices, default='option1') print(f"Selected: {selected_choice}") # Example without padding selected_choice_no_padding = prompt_for_choice(choices, padding=False) print(f"Selected (no padding): {selected_choice_no_padding}") # Example demonstrating error for empty choices (will raise ValueError) # try: # prompt_for_choice([]) # except ValueError as e: # print(e) ``` -------------------------------- ### Format and Parse Paths with Python Source: https://context7.com/xolox/python-humanfriendly/llms.txt Shortens absolute paths by abbreviating the home directory or expands user-friendly paths containing tildes and environment variables into absolute paths. ```python from humanfriendly import format_path, parse_path import os # Format paths (abbreviate home directory) home = os.environ.get('HOME', '/home/user') print(format_path(os.path.join(home, '.config', 'app.conf'))) # Output: '~/.config/app.conf' # Parse paths (expand tildes and variables) print(parse_path('~/Documents')) # Output: '/home/user/Documents' print(parse_path('$HOME/.bashrc')) # Output: '/home/user/.bashrc' ``` -------------------------------- ### Format File Sizes with Humanfriendly CLI Source: https://context7.com/xolox/python-humanfriendly/llms.txt Shows how to use the humanfriendly CLI to format large byte counts into human-readable formats like GB or GiB. Supports both SI (1000-based) and binary (1024-based) prefixes. ```bash # Format file sizes $ humanfriendly --format-size=1500000000 1.5 GB $ humanfriendly --format-size=1073741824 --binary 1 GiB ``` -------------------------------- ### Format Pathname with Home Directory Abbreviation (Python) Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Shortens an absolute pathname by abbreviating the user's home directory to '~'. This function is useful for displaying file paths in a more concise manner without losing essential information. It works with absolute path strings. ```python from os import environ from os.path import join from humanfriendly import format_path vimrc = join(environ['HOME'], '.vimrc') print(format_path(vimrc)) ``` -------------------------------- ### humanfriendly.usage APIs Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md APIs for parsing and reformatting usage messages, including finding meta variables and formatting usage strings. ```APIDOC ## humanfriendly.usage.find_meta_variables(usage_text) ### Description Find the meta variables in the given usage message. ### Method N/A (Python function) ### Endpoint N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **usage_text** (string) - Required - The usage message to parse. ### Request Example ```python from humanfriendly.usage import find_meta_variables find_meta_variables("--option=ARG") ``` ### Response #### Success Response (200) * **list** (list) - A list of strings with any meta variables found. #### Response Example ```json [ "ARG" ] ``` ## humanfriendly.usage.format_usage(usage_text) ### Description Highlight special items in a usage message, such as command line options and meta variables. ### Method N/A (Python function) ### Endpoint N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **usage_text** (string) - Required - The usage message to process. ### Request Example ```python from humanfriendly.usage import format_usage format_usage("Usage: --option=ARG") ``` ### Response #### Success Response (200) * **string** - The usage message with special items highlighted. #### Response Example ```json "Usage: --option=ARG" ``` ## humanfriendly.usage.import_module(name, package=None) ### Description Import a module, with support for relative imports using a specified package as an anchor. ### Method N/A (Python function) ### Endpoint N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **name** (string) - Required - The name of the module to import. * **package** (string) - Optional - The package to use as the anchor for relative imports. ### Request Example ```python import_module('my_module', package='my_package') ``` ### Response #### Success Response (200) * **module** - The imported module object. #### Response Example ```json ``` ``` -------------------------------- ### Enable Sphinx Customizations Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Configures the humanfriendly.sphinx module as a Sphinx extension. This enables all provided features automatically when added to the extensions list in conf.py. ```python # Sphinx extension module names. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'humanfriendly.sphinx', ] ``` -------------------------------- ### Format Timespans with Humanfriendly CLI Source: https://context7.com/xolox/python-humanfriendly/llms.txt Demonstrates using the humanfriendly CLI to convert a total number of seconds into a more readable timespan format, such as hours and minutes. ```bash # Format timespans $ humanfriendly --format-timespan=3665 1 hour and 1 minute ``` -------------------------------- ### Format Smart Table in Python Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Renders tabular data using the most appropriate representation based on content and terminal width. It intelligently chooses between `format_pretty_table` and `format_robust_table` to ensure optimal display. This function is ideal for general-purpose table rendering in terminals. ```python from humanfriendly.tables import format_smart_table column_names = ['Version', 'Uploaded on', 'Downloads'] humanfriendly_releases = [ ['1.23', '2015-05-25', '218'], ['1.23.1', '2015-05-26', '1354'], ['1.24', '2015-05-26', '223'], ['1.25', '2015-05-26', '4319'], ['1.25.1', '2015-06-02', '197'], ] print(format_smart_table(humanfriendly_releases, column_names)) ``` -------------------------------- ### Decorators Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Utility decorators for simplifying common Python programming patterns. ```APIDOC ## [PROPERTY] humanfriendly.decorators.RESULTS_ATTRIBUTE ### Description Defines the attribute name used by decorators to cache function results. ### Type - **string** - Default: 'cached_results' ``` -------------------------------- ### format_size Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Converts a byte count into a human-readable file size string. ```APIDOC ## FUNCTION humanfriendly.format_size ### Description Format a byte count as a human readable file size (KB, MB, GB, etc.). ### Parameters #### Arguments - **num_bytes** (int) - Required - The size in bytes. - **keep_width** (bool) - Optional - Whether to keep trailing zeros. - **binary** (bool) - Optional - Use binary (base-2) multiples if True, decimal (base-10) if False. ### Response - **Returns** (string) - The formatted file size. ### Example ```python format_size(1024, binary=True) # '1 KiB' ``` ``` -------------------------------- ### FUNCTION humanfriendly.tables.format_pretty_table Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Renders a collection of data into a human-readable ASCII table with borders. ```APIDOC ## FUNCTION humanfriendly.tables.format_pretty_table ### Description Render a table using characters like dashes and vertical bars to emulate borders. This function automatically right-aligns numeric columns for better readability. ### Method N/A (Python Function) ### Parameters #### Arguments - **data** (iterable) - Required - An iterable containing the rows of the table, where each row is an iterable of strings. - **column_names** (iterable) - Optional - An iterable of column names (strings). - **horizontal_bar** (string) - Optional - The character used to represent a horizontal bar (default: '-'). - **vertical_bar** (string) - Optional - The character used to represent a vertical bar (default: '|'). ### Request Example ```python from humanfriendly.tables import format_pretty_table column_names = ['Version', 'Downloads'] data = [['1.23', '218'], ['1.24', '223']] print(format_pretty_table(data, column_names)) ``` ### Response #### Success Response - **return** (string) - The rendered ASCII table as a string. ``` -------------------------------- ### Format Data into Pretty ASCII Tables Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md The `format_pretty_table` function renders tabular data using characters like dashes and vertical bars to create borders, suitable for terminal output. It supports custom characters for horizontal and vertical bars. Numeric columns are right-aligned for easier comparison, and column names are highlighted. This function is not optimized for performance due to its intended use case. ```python from humanfriendly.tables import format_pretty_table column_names = ['Version', 'Uploaded on', 'Downloads'] humanfriendly_releases = [ ['1.23', '2015-05-25', '218'], ['1.23.1', '2015-05-26', '1354'], ['1.24', '2015-05-26', '223'], ['1.25', '2015-05-26', '4319'], ['1.25.1', '2015-06-02', '197'], ] print(format_pretty_table(humanfriendly_releases, column_names)) ``` -------------------------------- ### Render Usage Message to reStructuredText (Python) Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Reformats a plain text command-line usage message into reStructuredText format. This function takes the raw usage text as input and outputs a string suitable for inclusion in .rst files. ```python from humanfriendly.usage import render_usage plain_usage = "Usage: my_program [OPTIONS] ARGUMENT\n\nThis is a sample program.\n\nSupported options:\n -h, --help\n Show this help message and exit." rendered_rst = render_usage(plain_usage) ``` -------------------------------- ### Format Byte Count as Human-Readable File Size (Python) Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Converts a byte count into a human-readable string representation (e.g., KB, MB, GB). Supports both decimal (base-10) and binary (base-2) multiples. An option to keep trailing zeros is available. ```python from humanfriendly import format_size print(format_size(0)) print(format_size(1)) print(format_size(5)) print(format_size(1000)) print(format_size(1024, binary=True)) print(format_size(1000 ** 3 * 4)) ``` -------------------------------- ### Format strings with humanfriendly.text.format Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md The format function provides a robust wrapper for string interpolation using both %-style and str.format() syntax. It prevents common errors associated with tuple interpolation and simplifies complex formatting expressions. ```python from humanfriendly.text import format # Basic interpolation print(format('the magic number is %s', 42)) # Handling tuple values safely value = (12, 42) print(format('the magic value is %s', value)) # Using keyword arguments print(format("{adjective} example", adjective='silly')) ``` -------------------------------- ### Format tabular data as ASCII tables Source: https://context7.com/xolox/python-humanfriendly/llms.txt Renders lists of data into readable ASCII table formats using pretty, robust, or smart formatting styles. ```python from humanfriendly.tables import format_pretty_table, format_smart_table data = [['1.0', '2023-01-15', '1,234'], ['1.1', '2023-02-20', '5,678']] headers = ['Version', 'Released', 'Downloads'] print(format_pretty_table(data, headers)) print(format_smart_table(data, headers)) ``` -------------------------------- ### Track Operation Duration with Timer Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md The Timer class provides a simple interface to track the duration of operations, supporting both standard and resumable timing modes. ```python from humanfriendly import Timer # Initialize a timer with Timer() as t: # Perform long running operation pass print(f"Operation took {t.elapsed_time} seconds") ``` -------------------------------- ### parse_usage Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Parses a plain text usage message by inferring its structure based on standard command-line help formats. ```APIDOC ## FUNCTION humanfriendly.usage.parse_usage ### Description Parses a usage message string into structured components, separating the introduction from the command-line options. ### Parameters #### Arguments - **text** (string) - Required - The raw usage message text to parse. ### Response #### Success Response (200) - **tuple** (list, list) - Returns a tuple containing: 1. A list of introduction paragraphs. 2. A list of alternating command-line options and their descriptions. ### Response Example { "introduction": ["Usage: program [OPTIONS]"], "options": ["-v, --verbose", "Make more noise."] } ``` -------------------------------- ### humanfriendly.prompts.MAX_ATTEMPTS Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Constant defining the maximum number of attempts for interactive prompts before raising an error. ```APIDOC ## humanfriendly.prompts.MAX_ATTEMPTS ### Description The number of times an interactive prompt is shown on invalid input. ### Method Constant ### Endpoint N/A (Python constant) ### Parameters None ### Request Example ```python import humanfriendly.prompts print(humanfriendly.prompts.MAX_ATTEMPTS) ``` ### Response #### Success Response (200) - **Returns** (int) - The maximum number of attempts allowed for invalid input. #### Response Example ```json 10 ``` ``` -------------------------------- ### Parse Human-Readable Data Sizes Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Converts strings representing data sizes (like '1 KB' or '1.5 GB') into integer byte counts. Supports both decimal and binary base calculations via the binary parameter. ```python from humanfriendly import parse_size print(parse_size('1 KB')) print(parse_size('1 KiB')) print(parse_size('1 KB', binary=True)) print(parse_size('1.5 GB', binary=True)) ``` -------------------------------- ### Format Numbers with Separators using Humanfriendly CLI Source: https://context7.com/xolox/python-humanfriendly/llms.txt Shows the humanfriendly CLI's capability to format large numbers by adding standard thousands separators for better readability. ```bash # Format numbers with separators $ humanfriendly --format-number=1234567890 1,234,567,890 ``` -------------------------------- ### humanfriendly.format_length(num_metres, keep_width=False) Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Formats a length in meters into a human-readable string, supporting units from nanometers to kilometers. ```APIDOC ## POST /humanfriendly/format_length ### Description Format a metre count as a human readable length. Supports ranges from nanometres to kilometres. ### Method POST ### Endpoint `/humanfriendly/format_length` ### Parameters #### Path Parameters N/A #### Query Parameters - **keep_width** (boolean) - Optional. If `True`, trailing zeros are not stripped. #### Request Body - **num_metres** (float or integer) - The length to format in metres. ### Request Example ```json { "num_metres": 1500.5, "keep_width": false } ``` ### Response #### Success Response (200) - **formatted_length** (string) - The human readable length. #### Response Example ```json { "formatted_length": "1.5 km" } ``` ``` -------------------------------- ### humanfriendly.text.split Source: https://github.com/xolox/python-humanfriendly/blob/master/docs/api.md Splits a comma-separated list of strings, handling whitespace and empty strings. ```APIDOC ## humanfriendly.text.split(text, delimiter=',') ### Description Split a comma-separated list of strings. ### Parameters #### Path Parameters - **text** (string) - Required - The text to split. - **delimiter** (string) - Optional - The delimiter to split on. Defaults to ','. ### Returns - **list** - A list of zero or more non-empty strings. ### Example ```pycon >>> from humanfriendly.text import split >>> split('foo,bar, baz,') ['foo', 'bar', 'baz'] ``` ### Notes This function provides cleaner output than Python's built-in `str.split()` by default, omitting empty strings and leading/trailing whitespace within elements. ``` -------------------------------- ### Format File Size (Python) Source: https://context7.com/xolox/python-humanfriendly/llms.txt Converts byte counts into human-readable file size strings using decimal or binary multiples. Supports various units from bytes to yottabytes and can maintain a consistent output width. ```python from humanfriendly import format_size # Basic usage - decimal multiples (default) print(format_size(0)) # Output: '0 bytes' print(format_size(1)) # Output: '1 byte' print(format_size(1000)) # Output: '1 KB' print(format_size(1500000)) # Output: '1.5 MB' print(format_size(4000000000)) # Output: '4 GB' # Binary multiples (base-2) print(format_size(1024, binary=True)) # Output: '1 KiB' print(format_size(1073741824, binary=True)) # Output: '1 GiB' # Keep trailing zeros for consistent width print(format_size(1000000, keep_width=True)) # Output: '1.00 MB' ```