### 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