Typing stubs for click - a command line interface creation kit for Python
Interactive CLI elements including prompts, confirmation dialogs, progress bars, styled output, and terminal utilities for building rich command-line experiences.
Core functions for displaying text and information to users.
def echo(
message: object = None,
file: IO[str] | None = None,
nl: bool = True,
err: bool = False,
color: bool | None = None
) -> None:
"""
Print a message to stdout or stderr.
Parameters:
- message: Message to print (any object)
- file: File object to write to (defaults to stdout)
- nl: Add newline at end
- err: Write to stderr instead of stdout
- color: Enable/disable color output
Usage:
click.echo('Hello World')
click.echo('Error occurred', err=True)
click.echo('No newline', nl=False)
"""
def secho(
message: str | None = None,
file: IO[Any] | None = None,
nl: bool = True,
err: bool = False,
color: bool | None = None,
fg: str | None = None,
bg: str | None = None,
bold: bool | None = None,
dim: bool | None = None,
underline: bool | None = None,
blink: bool | None = None,
reverse: bool | None = None,
reset: bool = True,
) -> None:
"""
Print a styled message.
Parameters:
- message: Message to print
- file: File object to write to
- nl: Add newline at end
- err: Write to stderr instead of stdout
- color: Enable/disable color output
- fg: Foreground color ('red', 'green', 'blue', etc.)
- bg: Background color
- bold: Make text bold
- dim: Make text dim
- underline: Underline text
- blink: Make text blink
- reverse: Reverse colors
- reset: Reset styling after message
Usage:
click.secho('Success!', fg='green', bold=True)
click.secho('Warning', fg='yellow')
click.secho('Error', fg='red', err=True)
"""Functions for styling text with colors and formatting.
def style(
text: str,
fg: str | None = None,
bg: str | None = None,
bold: bool | None = None,
dim: bool | None = None,
underline: bool | None = None,
blink: bool | None = None,
reverse: bool | None = None,
reset: bool = True,
) -> str:
"""
Style text with ANSI color codes.
Parameters:
- text: Text to style
- fg: Foreground color
- bg: Background color
- bold: Make text bold
- dim: Make text dim
- underline: Underline text
- blink: Make text blink
- reverse: Reverse colors
- reset: Reset styling after text
Returns:
Styled text string
Colors: black, red, green, yellow, blue, magenta, cyan, white, bright_black,
bright_red, bright_green, bright_yellow, bright_blue, bright_magenta,
bright_cyan, bright_white
Usage:
styled = click.style('Important', fg='red', bold=True)
click.echo(styled)
# Or use secho directly
click.secho('Important', fg='red', bold=True)
"""
def unstyle(text: str) -> str:
"""
Remove ANSI styling from text.
Parameters:
- text: Styled text
Returns:
Plain text without styling
Usage:
plain = click.unstyle('\x1b[31mRed Text\x1b[0m')
# plain == 'Red Text'
"""Functions for gathering input from users interactively.
def prompt(
text: str,
default: str | None = None,
hide_input: bool = False,
confirmation_prompt: bool = False,
type: _ConvertibleType | None = None,
value_proc: Callable[[str | None], Any] | None = None,
prompt_suffix: str = ': ',
show_default: bool = True,
err: bool = False,
show_choices: bool = True,
) -> Any:
"""
Prompt user for input.
Parameters:
- text: Prompt text
- default: Default value if user presses enter
- hide_input: Hide input (for passwords)
- confirmation_prompt: Ask for confirmation (enter twice)
- type: Type for value conversion
- value_proc: Custom value processor
- prompt_suffix: Text after prompt
- show_default: Show default value in prompt
- err: Show prompt on stderr
- show_choices: Show choices for Choice type
Returns:
User input (converted to specified type)
Usage:
name = click.prompt('Your name')
age = click.prompt('Your age', type=int)
password = click.prompt('Password', hide_input=True)
email = click.prompt('Email', default='user@example.com')
"""
def confirm(
text: str,
default: bool = False,
abort: bool = False,
prompt_suffix: str = ' [y/N]: ',
show_default: bool = True,
err: bool = False,
) -> bool:
"""
Prompt for yes/no confirmation.
Parameters:
- text: Confirmation text
- default: Default choice (True for yes, False for no)
- abort: Abort if user chooses no
- prompt_suffix: Text after prompt
- show_default: Show default in prompt
- err: Show prompt on stderr
Returns:
True for yes, False for no
Usage:
if click.confirm('Delete all files?'):
delete_files()
# Abort if user says no
click.confirm('Continue?', abort=True)
"""
def getchar(echo: bool = False) -> str:
"""
Get a single character from input.
Parameters:
- echo: Echo the character
Returns:
Single character string
Usage:
click.echo('Press any key to continue...')
key = click.getchar()
click.echo(f'You pressed: {key}')
"""Visual progress indicators for long-running operations.
def progressbar(
iterable: Iterable | None = None,
length: int | None = None,
label: str | None = None,
show_eta: bool = True,
show_percent: bool | None = None,
show_pos: bool = False,
item_show_func: Callable[[Any], str] | None = None,
fill_char: str = '#',
empty_char: str = '-',
bar_template: str = '%(label)s [%(bar)s] %(info)s',
info_sep: str = ' ',
width: int = 36,
file: IO[Any] | None = None,
color: bool | None = None,
) -> ProgressBar:
"""
Create a progress bar context manager.
Parameters:
- iterable: Iterable to track progress for
- length: Total number of items (if iterable not provided)
- label: Progress bar label
- show_eta: Show estimated time remaining
- show_percent: Show percentage complete
- show_pos: Show current position
- item_show_func: Function to display current item
- fill_char: Character for completed portion
- empty_char: Character for remaining portion
- bar_template: Template for progress bar display
- info_sep: Separator for info sections
- width: Width of progress bar
- file: File to write to
- color: Enable colored progress bar
Returns:
ProgressBar context manager
Usage:
# With iterable
items = ['file1.txt', 'file2.txt', 'file3.txt']
with click.progressbar(items, label='Processing files') as bar:
for item in bar:
process_file(item)
# Manual progress
with click.progressbar(length=100, label='Training model') as bar:
for i in range(100):
train_step()
bar.update(1)
# Show current item
def show_item(item):
return f'Processing {item}'
with click.progressbar(files, item_show_func=show_item) as bar:
for file in bar:
process_file(file)
"""Internal utility functions used by other terminal UI functions.
def hidden_prompt_func(prompt: str) -> str:
"""
Internal function for password prompts.
Parameters:
- prompt: Prompt text to display
Returns:
Hidden input string
"""
def _build_prompt(
text: str,
suffix: str,
show_default: bool = True,
default: str | None = None
) -> str:
"""
Internal function to build prompt strings.
Parameters:
- text: Base prompt text
- suffix: Prompt suffix (e.g., ': ')
- show_default: Whether to show default value
- default: Default value
Returns:
Formatted prompt string
"""Utility functions for terminal operations and information.
def get_terminal_size() -> tuple[int, int]:
"""
Get terminal size.
Returns:
Tuple of (width, height) in characters
Usage:
width, height = click.get_terminal_size()
click.echo(f'Terminal: {width}x{height}')
"""
def clear() -> None:
"""
Clear the terminal screen.
Usage:
click.clear()
click.echo('Screen cleared!')
"""
def pause(info: str = 'Press any key to continue...', err: bool = False) -> None:
"""
Pause execution until user presses a key.
Parameters:
- info: Text to display
- err: Show message on stderr
Usage:
click.echo('Processing complete.')
click.pause()
"""Utility functions for file handling and stream operations.
def get_binary_stream(name: str) -> IO[bytes]:
"""
Get a binary stream (stdin/stdout/stderr).
Parameters:
- name: Stream name ('stdin', 'stdout', 'stderr')
Returns:
Binary stream object
Usage:
stdout_binary = click.get_binary_stream('stdout')
stdout_binary.write(b'Binary data')
"""
def get_text_stream(name: str, encoding: str | None = None, errors: str = 'strict') -> IO[str]:
"""
Get a text stream (stdin/stdout/stderr).
Parameters:
- name: Stream name ('stdin', 'stdout', 'stderr')
- encoding: Text encoding (None for default)
- errors: Error handling strategy
Returns:
Text stream object
Usage:
stdout_text = click.get_text_stream('stdout', encoding='utf-8')
stdout_text.write('Text data')
"""
def open_file(
filename: str,
mode: str = 'r',
encoding: str | None = None,
errors: str = 'strict',
lazy: bool = False,
atomic: bool = False,
) -> Any:
"""
Open a file with enhanced features.
Parameters:
- filename: File path to open
- mode: File mode ('r', 'w', 'a', etc.)
- encoding: Text encoding
- errors: Error handling strategy
- lazy: Use lazy file opening
- atomic: Use atomic file operations
Returns:
File object (IO, LazyFile, or KeepOpenFile)
Usage:
# Regular file opening
with click.open_file('data.txt') as f:
content = f.read()
# Lazy file opening
lazy_file = click.open_file('large.txt', lazy=True)
# Atomic file operations
with click.open_file('config.json', 'w', atomic=True) as f:
json.dump(data, f)
"""
def format_filename(filename: str, shorten: bool = False) -> str:
"""
Format a filename for display.
Parameters:
- filename: File path to format
- shorten: Shorten long paths
Returns:
Formatted filename string
Usage:
display_name = click.format_filename('/very/long/path/to/file.txt', shorten=True)
click.echo(f'Processing: {display_name}')
"""
def get_app_dir(app_name: str, roaming: bool = True, force_posix: bool = False) -> str:
"""
Get application data directory.
Parameters:
- app_name: Application name
- roaming: Use roaming profile on Windows
- force_posix: Force POSIX-style paths
Returns:
Application data directory path
Usage:
config_dir = click.get_app_dir('myapp')
config_file = os.path.join(config_dir, 'config.json')
"""
def get_os_args() -> list[str]:
"""
Get command line arguments from the OS.
Returns:
List of command line arguments
Usage:
args = click.get_os_args()
click.echo(f'Command line args: {args}')
"""Special file classes for advanced file handling scenarios.
class LazyFile:
name: str
mode: str
encoding: str | None
errors: str
atomic: bool
def __init__(
self,
filename: str,
mode: str = 'r',
encoding: str | None = None,
errors: str = 'strict',
atomic: bool = False,
) -> None:
"""
Lazy file that opens only when accessed.
Parameters:
- filename: File path
- mode: File mode
- encoding: Text encoding
- errors: Error handling strategy
- atomic: Use atomic operations
"""
def open(self) -> IO[Any]:
"""Open the file and return file object."""
def close(self) -> None:
"""Close the file if it's open."""
def close_intelligently(self) -> None:
"""Close file intelligently (don't close stdin/stdout/stderr)."""
def __enter__(self) -> LazyFile: ...
def __exit__(self, exctype, excinst, exctb) -> None: ...
def __iter__(self) -> Iterator[Any]: ...
class KeepOpenFile(Generic[AnyStr]):
def __init__(self, file: IO[AnyStr]) -> None:
"""
File wrapper that keeps file open.
Parameters:
- file: File object to wrap
"""
def __enter__(self) -> KeepOpenFile[AnyStr]: ...
def __exit__(self, exctype, excinst, exctb) -> None: ...
def __iter__(self) -> Iterator[AnyStr]: ...Helper functions for various operations.
def safecall(func: _T) -> _T:
"""
Safely call a function, handling exceptions.
Parameters:
- func: Function to call safely
Returns:
Function wrapper that handles exceptions
"""
def make_str(value: Any) -> str:
"""
Convert any value to string safely.
Parameters:
- value: Value to convert
Returns:
String representation of value
"""
def make_default_short_help(help: str, max_length: int = 45) -> str:
"""
Generate short help text from full help.
Parameters:
- help: Full help text
- max_length: Maximum length for short help
Returns:
Shortened help text
"""Functions for launching external programs and editors.
def edit(
text: str | None = None,
editor: str | None = None,
env: str | None = None,
require_save: bool = True,
extension: str = '.txt',
filename: str | None = None,
) -> str:
"""
Launch an editor to edit text.
Parameters:
- text: Initial text content
- editor: Editor command (uses $EDITOR if not specified)
- env: Environment variable for editor
- require_save: Require file to be saved
- extension: File extension for temporary file
- filename: Specific filename to use
Returns:
Edited text content
Usage:
# Edit empty text
content = click.edit()
# Edit existing content
config = load_config()
new_config = click.edit(config)
save_config(new_config)
# Use specific editor
text = click.edit(editor='nano')
"""
def launch(url: str, wait: bool = False, locate: bool = False) -> int:
"""
Launch a URL or file with the default application.
Parameters:
- url: URL or file path to launch
- wait: Wait for application to exit
- locate: Open file manager at location instead
Returns:
Exit code of launched application
Usage:
# Open URL in browser
click.launch('https://example.com')
# Open file with default application
click.launch('document.pdf')
# Open file manager at location
click.launch('/path/to/file', locate=True)
"""Display long text content with paging support.
def echo_via_pager(
text_or_generator: str | Iterable[str] | Callable[[], Generator[str, None, None]],
color: bool | None = None
) -> None:
"""
Display text through a pager (less, more, etc.).
Parameters:
- text_or_generator: Text to display (string, iterable, or generator function)
- color: Enable colored output in pager
Usage:
# Page long text
long_text = generate_report()
click.echo_via_pager(long_text)
# Page generator output
def generate_lines():
for i in range(1000):
yield f'Line {i}\\n'
click.echo_via_pager(generate_lines)
# Page list of strings
lines = ['Line 1', 'Line 2', 'Line 3'] * 100
click.echo_via_pager(lines)
"""Direct access to progress bar functionality.
class ProgressBar:
length: int | None
label: str
def update(self, n_steps: int) -> None:
"""
Update progress by n steps.
Parameters:
- n_steps: Number of steps to advance
"""
def finish(self) -> None:
"""
Complete the progress bar.
"""
def __enter__(self) -> ProgressBar: ...
def __exit__(self, exc_type, exc_val, exc_tb) -> None: ...
def __iter__(self) -> ProgressBar: ...
def __next__(self) -> Any: ...Install with Tessl CLI
npx tessl i tessl/pypi-types-click