consolekit
Additional utilities for click.
Docs |
|
---|---|
Tests |
|
PyPI |
|
Anaconda |
|
Activity |
|
QA |
|
Other |
Installation
python3 -m pip install consolekit --user
First add the required channels
conda config --add channels https://conda.anaconda.org/conda-forge
conda config --add channels https://conda.anaconda.org/domdfcoding
Then install
conda install consolekit
python3 -m pip install git+https://github.com/domdfcoding/consolekit@master --user
Additionally, for better support in terminals,
install psutil by specifying the terminals
extra:
python -m pip install consolekit[terminals]
or, if you installed consolekit
through conda:
conda install -c conda-forge psutil
Highlights
auto_default_option( *param_decls, **attrs, ) ->Callable
[[~_C
],~_C
]
Attaches an option to the command, with a default value determined from the decorated function’s signature.
See more in consolekit.options
.
MarkdownHelpCommand( name:Optional
[str
], context_settings:Optional
[MutableMapping
[str
,Any
]] =None
, callback:Optional
[Callable
[...,Any
]] =None
, params:Optional
[List
[Parameter
]] =None
, help:Optional
[str
] =None
, epilog:Optional
[str
] =None
, short_help:Optional
[str
] =None
, options_metavar:Optional
[str
] ='[OPTIONS]'
, add_help_option:bool
=True
, no_args_is_help:bool
=False
, hidden:bool
=False
, deprecated:bool
=False
, )
Subclass of click.Command
which treats the help text as markdown
and prints a rendered representation.
See more in consolekit.commands
.
SuggestionGroup( name:Optional
[str
] =None
, commands:Union
[MutableMapping
[str
,Command
],Sequence
[Command
],None
] =None
, **attrs:Any
, )
Subclass of click.Group
which suggests the most similar command if the command is not found.
See more in consolekit.commands
.
Contents
consolekit
Additional utilities for click.
Attention
consolekit
disables Python’s readline history to prevent unrelated histories appearing for prompts.
If the original behaviour is desired run:
import readline
readline.set_history_length(-1)
readline.set_auto_history(True)
Functions:
|
Shortcut to |
|
Shortcut to |
|
Shortcut to |
-
click_command
(name=None, cls=None, **attrs)[source] Shortcut to
click.command()
, with the-h
/--help
option enabled and a max width of120
.
-
click_group
(name=None, cls=None, **attrs)[source] Shortcut to
click.group()
, with the-h
/--help
option enabled and a max width of120
.
-
option
(*param_decls, **attrs)[source] Shortcut to
click.option()
, but usingconsolekit.input.confirm()
when prompting for a boolean flag.- Parameters
*param_decls (
str
)**attrs (
Any
) – Additional keyword arguments passed toclick.command()
.
- Return type
Callable
[[~_C
],~_C
]
consolekit.commands
Customised click commands and command groups.
New in version 0.8.0.
Classes:
|
Subclass of |
|
Subclass of |
|
Subclass of |
Mixin class for |
|
|
Subclass of |
|
Subclass of |
Mixin class for |
|
|
Subclass of |
-
class
ContextInheritingGroup
(name=None, commands=None, **attrs)[source] Bases:
Group
Subclass of
click.Group
whose children inherit itscontext_settings
.The group’s commands can be given different context settings by passing the
context_settings
keyword argument tocommand()
andgroup()
as normal.New in version 1.1.0.
Methods:
command
(*args, **kwargs)A shortcut decorator for declaring and attaching a command to the group.
group
(*args, **kwargs)A shortcut decorator for declaring and attaching a group to the group.
-
command
(*args, **kwargs)[source] A shortcut decorator for declaring and attaching a command to the group.
This takes the same arguments as
click.command()
but immediately registers the created command with this instance by calling intoclick.Group.add_command()
.
-
group
(*args, **kwargs)[source] A shortcut decorator for declaring and attaching a group to the group.
This takes the same arguments as
click.group()
but immediately registers the created group with this instance by calling intoclick.Group.add_command()
.
-
-
class
MarkdownHelpCommand
[source] -
class
MarkdownHelpGroup
[source] Bases:
MarkdownHelpMixin
Subclasses of
click.Command
andclick.Group
which treat the help text as markdown and print a rendered representation.Tested in Gnome Terminal and Terminator (both libVTE-based), and PyCharm. libVTE has the best support. PyCharm’s support for italics and strikethrough is poor. Support on Windows is, as expected, poor.
Not tested on other terminals, but contributions are welcome to improve support.
New in version 0.8.0.
-
class
MarkdownHelpMixin
[source] Bases:
object
Mixin class for
click.Command
andclick.Group
which treats the help text as markdown and prints a rendered representation.See also
Tip
This can be combined with groups such as
SuggestionGroup
.Tested in Gnome Terminal and Terminator (both libVTE-based), and PyCharm. libVTE has the best support. PyCharm’s support for italics and strikethrough is poor. Support on Windows is, as expected, poor.
Not tested on other terminals, but contributions are welcome to improve support.
New in version 0.8.0.
-
format_help_text
(ctx, formatter)[source] Writes the help text to the formatter if it exists.
- Parameters
ctx (
Context
)formatter (
HelpFormatter
)
-
-
class
RawHelpCommand
[source] -
class
RawHelpGroup
[source] Bases:
RawHelpMixin
Subclasses of
click.Command
andclick.Group
which leave the help text unformatted.New in version 0.8.0.
-
class
RawHelpMixin
[source] Bases:
object
Mixin class for
click.Command
andclick.Group
which leaves the help text unformatted.See also
Tip
This can be combined with groups such as
SuggestionGroup
.New in version 0.8.0.
-
format_help_text
(ctx, formatter)[source] Writes the help text to the formatter if it exists.
- Parameters
ctx (
Context
)formatter (
HelpFormatter
)
-
-
class
SuggestionGroup
(name=None, commands=None, **attrs)[source] Bases:
ContextInheritingGroup
Subclass of
click.Group
which suggests the most similar command if the command is not found.Changed in version 0.8.0: Moved to
consolekit.commands
.Changed in version 1.1.0: Now inherits from
ContextInheritingGroup
consolekit.input
Input functions (prompt, choice etc.).
Functions:
|
Prompts a user for input. |
|
Prompts for confirmation (yes/no question). |
|
Prompts a user for input. |
|
Read a string from standard input, but prompt to standard error. |
-
choice
(options, text='', default=None, prompt_suffix=': ', show_default=True, err=False, start_index=0)[source] Prompts a user for input.
If the user aborts the input by sending an interrupt signal, this function will catch it and raise a
click.Abort
exception.- Parameters
text (
str
) – The text to show for the prompt. Default''
.default (
Optional
[str
]) – The index of the default value to use if the user does not enter anything. If this is not given it will prompt the user until aborted. DefaultNone
.prompt_suffix (
str
) – A suffix that should be added to the prompt. Default': '
.show_default (
bool
) – Shows or hides the default value in the prompt. DefaultTrue
.err (
bool
) – IfTrue
the file defaults tostderr
instead ofstdout
, the same as with echo. DefaultFalse
.start_index (
int
) – Ifoptions
is a list of values, sets the start index. Default0
.
- Return type
- Overloads
-
confirm
(text, default=False, abort=False, prompt_suffix=': ', show_default=True, err=False)[source] Prompts for confirmation (yes/no question).
If the user aborts the input by sending a interrupt signal this function will catch it and raise a
click.Abort
exception.- Parameters
text (
str
) – The question to ask.abort (
bool
) – IfTrue
a negative answer aborts the exception by raisingclick.Abort
. DefaultFalse
.prompt_suffix (
str
) – A suffix that should be added to the prompt. Default': '
.show_default (
bool
) – Shows or hides the default value in the prompt. DefaultTrue
.err (
bool
) – IfTrue
the file defaults tostderr
instead ofstdout
, the same as with echo. DefaultFalse
.
-
prompt
(text, default=None, hide_input=False, confirmation_prompt=False, type=None, value_proc=None, prompt_suffix=': ', show_default=True, err=False, show_choices=True)[source] Prompts a user for input.
If the user aborts the input by sending an interrupt signal, this function will catch it and raise a
click.Abort
exception.- Parameters
text (
str
) – The text to show for the prompt.default (
Optional
[str
]) – The default value to use if no input happens. If this is not given it will prompt until it is aborted. DefaultNone
.hide_input (
bool
) – IfTrue
then the input value will be hidden. DefaultFalse
.confirmation_prompt (
Union
[bool
,str
]) – Asks for confirmation for the value. Can be set to a string instead ofTrue
to customize the message. DefaultFalse
.type (
Union
[type
,ParamType
,Tuple
[Union
[type
,ParamType
], …],Callable
[[str
],Any
],Callable
[[Optional
[str
]],Any
],None
]) – The type to check the value against. DefaultNone
.value_proc (
Optional
[Callable
[[Optional
[str
]],Any
]]) – If this parameter is provided it must be a function that is invoked instead of the type conversion to convert a value. DefaultNone
.prompt_suffix (
str
) – A suffix that should be added to the prompt. Default': '
.show_default (
bool
) – Shows or hides the default value in the prompt. DefaultTrue
.err (
bool
) – IfTrue
the file defaults tostderr
instead ofstdout
, the same as withclick.echo()
. DefaultFalse
.show_choices (
bool
) – Show or hide choices if the passed type is aclick.Choice
. For example, if the choice is eitherday
orweek
,show_choices
isTrue
andtext
is'Group by'
then the prompt will be'Group by (day, week): '
. DefaultTrue
.
-
stderr_input
(prompt='', file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source] Read a string from standard input, but prompt to standard error.
The trailing newline is stripped. If the user hits EOF (Unix: Ctrl-D, Windows: Ctrl-Z+Return), raise
EOFError
.On Unix, GNU readline is used if enabled.
The
prompt
string, if given, is printed to stderr without a trailing newline before reading.- Return type
consolekit.options
Command line options.
New in version 0.4.0.
Classes:
|
|
|
Subclass of |
Data:
Invariant |
|
Invariant |
Functions:
|
Attaches an argument to the command, with a default value determined from the decorated function’s signature. |
|
Attaches an option to the command, with a default value determined from the decorated function’s signature. |
|
Adds an option (via the parameter |
|
Decorator to a flag option to a click command. |
|
Decorator to add the |
|
Decorator to add the |
|
Adds an option (via the parameter |
|
Adds an option to show the version and exit. |
-
class
DescribedArgument
(*args, description=None, **kwargs)[source] Bases:
Argument
click.Argument
with an additional keyword argument and attribute giving a short description.This is not shown in the help text, but may be useful for manpages or HTML documentation where additional information can be provided.
New in version 1.2.0.
See
click.Argument
andclick.Parameter
for descriptions of the other keyword argu ments.
-
class
MultiValueOption
(param_decls=None, show_default=False, help=None, hidden=False, type=None, required=False, default=(), callback=None, metavar=None, expose_value=True, is_eager=False)[source] Bases:
Option
Subclass of
click.Option
that behaves like argparse’snargs='+'
.New in version 0.6.0.
- Parameters
param_decls (
Optional
[List
[str
]]) – The parameter declarations for this option or argument. This is a list of flags or argument names. DefaultNone
.show_default (
bool
) – Controls whether the default value should be shown on the help page. Normally, defaults are not shown. If this value is a string, it shows the string instead of the value. This is particularly useful for dynamic options. DefaultFalse
.hidden (
bool
) – Hide this option from help outputs. DefaultFalse
.type (
Union
[type
,ParamType
,Tuple
[Union
[type
,ParamType
], …],Callable
[[str
],Any
],Callable
[[Optional
[str
]],Any
],None
]) – The type that should be used. Either aclick.ParamType
or a Python type. The later is converted into the former automatically if supported. DefaultNone
.required (
bool
) – Controls whether this is optional. DefaultFalse
.default (
Optional
[Any
]) – The default value if omitted. This can also be a callable, in which case it is invoked when the default is needed without any arguments. Default()
.callback (
Optional
[Callable
[[Context
,Parameter
,str
],Any
]]) – A callback that should be executed after the parameter was matched. This is called asfn(ctx, param, value)
and needs to return the value. DefaultNone
.metavar (
Optional
[str
]) – How the value is represented in the help page. DefaultNone
.expose_value (
bool
) – IfTrue
then the value is passed onwards to the command callback and stored on the context, otherwise it is skipped. DefaultTrue
.is_eager (
bool
) – Eager values are processed before non eager ones. DefaultFalse
.
Example usage:
@click.option( "--select", type=click.STRING, help="The checks to enable", cls=MultiValueOption, ) @click_command() def main(select: Iterable[str]): select = list(select)
Methods:
add_to_parser
(parser, ctx)Add the
MultiValueOption
to the given parser.process_value
(ctx, value)Given a value and context, converts the value as necessary.
-
add_to_parser
(parser, ctx)[source] Add the
MultiValueOption
to the given parser.- Parameters
parser (
OptionParser
)ctx (
Context
)
- Return type
-
_A
= TypeVar(_A, bound=Argument) Type:
TypeVar
Invariant
TypeVar
bound toclick.Argument
.
-
_C
= TypeVar(_C, bound=Command) Type:
TypeVar
Invariant
TypeVar
bound toclick.Command
.
-
auto_default_argument
(*param_decls, **attrs)[source] Attaches an argument to the command, with a default value determined from the decorated function’s signature.
All positional arguments are passed as parameter declarations to
click.Argument
; all keyword arguments are forwarded unchanged (exceptcls
). This is equivalent to creating anclick.Argument
instance manually and attaching it to theclick.Command.params
list.New in version 0.8.0.
- Parameters
cls – the option class to instantiate. This defaults to
click.Argument
.- Return type
-
auto_default_option
(*param_decls, **attrs)[source] Attaches an option to the command, with a default value determined from the decorated function’s signature.
All positional arguments are passed as parameter declarations to
click.Option
; all keyword arguments are forwarded unchanged (exceptcls
). This is equivalent to creating anclick.Option
instance manually and attaching it to theclick.Command.params
list.New in version 0.7.0.
- Parameters
cls – the option class to instantiate. This defaults to
click.Option
.- Return type
-
colour_option
(help_text='Whether to use coloured output.')[source] Adds an option (via the parameter
colour
:bool
) to enable verbose output.New in version 0.4.0.
-
flag_option
(*args, default=False, **kwargs)[source] Decorator to a flag option to a click command.
New in version 0.7.0.
- Parameters
*args – Positional arguments passed to
click.option()
.default (
Optional
[bool
]) – The default state of the flag. DefaultFalse
.**kwargs – Keyword arguments passed to
click.option()
.
- Return type
-
force_option
(help_text)[source] Decorator to add the
-f / --force
option to a click command.The value is exposed via the parameter
force
:bool
.New in version 0.5.0.
-
no_pager_option
(help_text='Disable the output pager.')[source] Decorator to add the
--no-pager
option to a click command.The value is exposed via the parameter
no_pager
:bool
.New in version 0.5.0.
-
verbose_option
(help_text='Show verbose output.')[source] Adds an option (via the parameter
verbose
:int
) to enable verbose output.The option can be provided multiple times by the user.
New in version 0.4.0.
-
version_option
(callback)[source] Adds an option to show the version and exit.
The option can be provided multiple times by the user. The count is stored as an integer and passed as the third parameter to the callback function.
New in version 0.4.0.
- Parameters
callback (
Callable
[[Context
,Option
,int
],Any
]) – The callback to invoke when the option is provided.
The callback function might look like:
def version_callback(ctx: click.Context, param: click.Option, value: int): if not value or ctx.resilient_parsing: return if value > 1: click.echo(f"consolekit version {__version__}, Python {sys.version}") else: click.echo(f"consolekit version {__version__}") ctx.exit()
consolekit.terminal_colours
Functions for adding ANSI character codes to terminal print statements.
Classes:
|
ANSI Colour Codes for foreground colour. |
|
ANSI Colour Codes for background colour. |
|
ANSI Colour Codes for text style. |
Provides methods to control the cursor. |
|
alias of |
|
alias of |
|
|
Abstract base class for ANSI Codes. |
|
An ANSI escape sequence representing a colour. |
Data:
Functions:
|
Helper to get the default value of the color flag. |
|
Strip ANSI colour codes from the given string to return a plaintext output. |
-
class
AnsiFore
(*args, **kwargs)[source] Bases:
AnsiCodes
ANSI Colour Codes for foreground colour.
The colours can be used as a context manager, a string, or a function.
Valid values are:
BLACK
RED
GREEN
YELLOW
BLUE
MAGENTA
CYAN
WHITE
RESET
LIGHTBLACK_EX
LIGHTRED_EX
LIGHTGREEN_EX
LIGHTYELLOW_EX
LIGHTBLUE_EX
LIGHTMAGENTA_EX
LIGHTCYAN_EX
LIGHTWHITE_EX
This class is also available under the shorter alias
Fore
.
-
class
AnsiBack
(*args, **kwargs)[source] Bases:
AnsiCodes
ANSI Colour Codes for background colour.
The colours can be used as a context manager, a string, or a function.
Valid values are:
BLACK
RED
GREEN
YELLOW
BLUE
MAGENTA
CYAN
WHITE
RESET
LIGHTBLACK_EX
LIGHTRED_EX
LIGHTGREEN_EX
LIGHTYELLOW_EX
LIGHTBLUE_EX
LIGHTMAGENTA_EX
LIGHTCYAN_EX
LIGHTWHITE_EX
This class is also available under the shorter alias
Back
.
-
class
AnsiStyle
(*args, **kwargs)[source] Bases:
AnsiCodes
ANSI Colour Codes for text style.
Valid values are:
BRIGHT
DIM
NORMAL
Additionally,
AnsiStyle.RESET_ALL
can be used to reset the foreground and background colours as well as the text style.This class is also available under the shorter alias
Style
.
-
class
AnsiCursor
[source] Bases:
object
Provides methods to control the cursor.
Methods:
UP
([n])Moves the cursor up
n
lines.DOWN
([n])Moves the cursor down
n
lines.FORWARD
([n])Moves the cursor forward (right)
n
lines.BACK
([n])Moves the cursor backward (left)
n
lines.POS
([x, y])Moves the cursor to the given position.
HIDE
()Hides the cursor.
SHOW
()Shows the cursor.
-
Fore
alias of
consolekit.terminal_colours.AnsiFore
-
Back
alias of
consolekit.terminal_colours.AnsiBack
-
Style
-
class
Colour
(style: str, stack: Union[Deque[str], List[str]], reset: str)[source] Bases:
str
An ANSI escape sequence representing a colour.
The colour can be used as a context manager, a string, or a function.
- Parameters
Methods:
__call__
(text)Returns the given text in this colour.
from_code
(code[, background])Returns a
Colour
to create coloured text.from_256_code
(code[, background])Returns a
Colour
to create 256-colour text.from_rgb
(r, g, b[, background])Returns a
Colour
to create 24-bit coloured text.from_hex
(hex_colour[, background])Returns a
Colour
to create 24-bit coloured text.-
classmethod
from_code
(code, background=False)[source] Returns a
Colour
to create coloured text.The colour can be reset using
Fore.RESET
orBack.RESET
.New in version 0.9.0.
- Parameters
- Return type
Note
The
background
option only influences the reset value and the stack used. It will not handle conversion of foreground codes to background codes.
-
classmethod
from_256_code
(code, background=False)[source] Returns a
Colour
to create 256-colour text.The colour can be reset using
Fore.RESET
orBack.RESET
.New in version 0.9.0.
Note
Not all terminals support 256-colour mode.
- Parameters
- Return type
Note
The
background
option only influences the reset value and the stack used. It will not handle conversion of foreground codes to background codes.
-
classmethod
from_rgb
(r, g, b, background=False)[source] Returns a
Colour
to create 24-bit coloured text.The colour can be reset using
Fore.RESET
orBack.RESET
.New in version 0.9.0.
Note
Not all terminals support 24-bit colours.
- Parameters
- Return type
Note
The
background
option only influences the reset value and the stack used. It will not handle conversion of foreground codes to background codes.
-
classmethod
from_hex
(hex_colour, background=False)[source] Returns a
Colour
to create 24-bit coloured text.The colour can be reset using
Fore.RESET
orBack.RESET
.New in version 0.9.0.
Note
Not all terminals support 24-bit colours.
- Parameters
- Return type
Note
The
background
option only influences the reset value and the stack used. It will not handle conversion of foreground codes to background codes.
-
resolve_color_default
(color=None)[source] Helper to get the default value of the color flag.
If a value is passed it is returned unchanged, otherwise it’s looked up from the current context.
If the environment variable
PYCHARM_HOSTED
is1
(which is the case if running in PyCharm) the output will be coloured by default.If the environment variable
NO_COLOR
is1
the output will not be coloured by default. See https://no-color.org/ for more details. This variable takes precedence overPYCHARM_HOSTED
.If no value is passed in, there is no context, and neither environment variable is set,
None
is returned.Changed in version 1.3.0:Added support for the
NO_COLOR
environment variable.Only uses a value from the click context (
Context.color
) if it is notNone
. Otherwise falls back to checking the environment variables.
consolekit.testing
Test helpers.
New in version 0.9.0.
Attention
This module has the following additional requirements:
coincidence>=0.1.0 pytest>=6.0.0 pytest-regressions>=2.0.2
These can be installed as follows:
python -m pip install consolekit[testing]
Classes:
|
Provides functionality to invoke and test a Click script in an isolated environment. |
|
Holds the captured result of an invoked CLI script. |
Functions:
Returns a click runner for this test function. |
-
class
CliRunner
(charset='UTF-8', env=None, *, echo_stdin=False, mix_stderr=True)[source] Bases:
CliRunner
Provides functionality to invoke and test a Click script in an isolated environment.
This only works in single-threaded systems without any concurrency as it changes the global interpreter state.
- Parameters
charset (
str
) – The character set for the input and output data. Default'UTF-8'
.env (
Optional
[Mapping
[str
,str
]]) – A dictionary with environment variables to override. DefaultNone
.echo_stdin (
bool
) – IfTrue
, then reading from stdin writes to stdout. This is useful for showing examples in some circumstances. Note that regular prompts will automatically echo the input. DefaultFalse
.mix_stderr (
bool
) – IfFalse
, then stdout and stderr are preserved as independent streams. This is useful for Unix-philosophy apps that have predictable stdout and noisy stderr, such that each may be measured independently. DefaultTrue
.
-
invoke
(cli, args=None, input=None, env=None, *, catch_exceptions=False, color=False, **extra)[source] Invokes a command in an isolated environment.
The arguments are forwarded directly to the command line script, the
extra
keyword arguments are passed to themain()
function of the command.- Parameters
cli (
BaseCommand
) – The command to invoke.args (
Union
[str
,Iterable
[str
],None
]) – The arguments to invoke. It may be given as an iterable or a string. When given as string it will be interpreted as a Unix shell command. More details atshlex.split()
. DefaultNone
.input (
Union
[bytes
,str
,IO
,None
]) – The input data forsys.stdin
. DefaultNone
.env (
Optional
[Mapping
[str
,str
]]) – The environment overrides. DefaultNone
.catch_exceptions (
bool
) – Whether to catch any other exceptions thanSystemExit
. DefaultFalse
.color (
bool
) – whether the output should contain color codes. The application can still override this explicitly. DefaultFalse
.**extra – The keyword arguments to pass to
click.Command.main()
.
- Return type
-
class
Result
(runner, stdout_bytes, stderr_bytes, exit_code, exception, exc_info=None)[source] Bases:
Result
Holds the captured result of an invoked CLI script.
- Parameters
runner (
CliRunner
) – The runner that created the result.stdout_bytes (
bytes
) – The standard output as bytes.stderr_bytes (
Optional
[bytes
]) – The standard error as bytes, orNone
if not available.exit_code (
int
) – The command’s exit code.exception (
Optional
[BaseException
]) – The exception that occurred, if any.exc_info (
Optional
[Tuple
[Type
[BaseException
],BaseException
,traceback
]]) – The traceback, if an exception occurred. DefaultNone
.
Methods:
check_stdout
(file_regression[, extension])Perform a regression check on the standard output from the command.
Attributes:
The (standard) output as a string.
The standard error as a string.
The standard output as a string.
consolekit.tracebacks
Functions for handling exceptions and their tracebacks.
New in version 1.0.0.
Classes:
|
Context manager to abort execution with a short error message on the following exception types: |
Functions:
|
Context manager to conditionally handle tracebacks, usually based on the value of a command line flag. |
Context manager to abort execution with a short error message on the following exception types: |
|
|
Decorator to add the |
-
class
TracebackHandler
(exception=Abort())[source] Bases:
object
Context manager to abort execution with a short error message on the following exception types:
Other custom exception classes inheriting from
Exception
are also handled, but with a generic message.The following exception classes are ignored:
SystemExit
(new in version 1.1.2)
How these exceptions are handled can be changed, and supported can be added for further exception classes by subclassing this class. Each method is named in the form
handle_<exception>
, whereexception
is the name of the exception class to handle.New in version 1.0.0.
- Parameters
exception (
BaseException
) – The exception to raise after handling the traceback. If not running within a click command or group you’ll likely want to set this toSystemExit(1)
. Defaultclick.Abort()
.
Changed in version 1.4.0: Added the
exception
argument.See also
Methods:
__call__
()Use the
TracebackHandler
with awith
block, and handle any exceptions raised within.abort
(msg)Abort the current process by calling
self.exception
.handle
(e)Handle the given exception.
Attributes:
The exception to raise after handling the traceback.
-
__call__
()[source] Use the
TracebackHandler
with awith
block, and handle any exceptions raised within.
-
exception
Type:
Exception
The exception to raise after handling the traceback.
New in version 1.4.0.
-
handle
(e)[source] Handle the given exception.
- Parameters
e (
BaseException
)- Return type
-
handle_tracebacks
(show_traceback=False, cls=<class 'TracebackHandler'>)[source] Context manager to conditionally handle tracebacks, usually based on the value of a command line flag.
New in version 0.8.0.
- Parameters
show_traceback (
bool
) – IfTrue
, the full Python traceback will be shown on errors. IfFalse
, only the summary of the traceback will be shown. In either case the program execution will stop on error. DefaultFalse
.cls (
Type
[TracebackHandler
]) – The class to use to handle the tracebacks. Defaultconsolekit.tracebacks.TracebackHandler
.
- Return type
Changed in version 1.0.0: Added the
cls
parameter.See also
-
traceback_handler
()[source] Context manager to abort execution with a short error message on the following exception types:
Other custom exception classes inheriting from
Exception
are also handled, but with a generic message.The following exception classes are ignored:
New in version 0.8.0.
See also
consolekit.utils
Utility functions.
Changed in version 1.0.0: traceback_handler()
and handle_tracebacks()
moved to consolekit.tracebacks
.
They will still be importable from here until v2.0.0
Classes:
|
Mistletoe markdown renderer for terminals. |
Functions:
|
Aborts the program execution. |
|
Compare two sequences of lines; generate the delta as a unified diff. |
Context manager to hide the cursor for the scope of the |
|
Hide the cursor. |
|
|
Returns a list of all commands. |
|
Return whether |
|
Echo |
|
Print |
Show the cursor. |
Data:
|
|
|
|
|
-
class
TerminalRenderer
(*extras, **kwargs)[source] Bases:
BaseRenderer
Mistletoe markdown renderer for terminals.
Tested in Gnome Terminal and Terminator (both libVTE-based), and PyCharm. libVTE has the best support. PyCharm’s support for italics and strikethrough is poor. Support on Windows is, as expected, poor.
Not tested on other terminals, but contributions are welcome to improve support.
New in version 0.8.0.
Methods:
render
(token)Render the given token for display in a terminal.
render_emphasis
(token)Render emphasis (
*emphasis*
).render_inline_code
(token)Render inline code (
`code`
).render_line_break
(token)Render a line break in a multiline paragraph.
render_list
(token)Render a markdown list.
render_list_item
(token)Render a markdown list item.
render_paragraph
(token)Render a paragraph.
render_strikethrough
(token)Render strikethrough (
~~strikethrough~~
).render_strong
(token)Render strong (
**strong**
).-
render
(token)[source] Render the given token for display in a terminal.
- Parameters
token
- Return type
-
render_emphasis
(token)[source] Render emphasis (
*emphasis*
).- Parameters
token (
Emphasis
) – The token to render.- Return type
-
render_inline_code
(token)[source] Render inline code (
`code`
).- Parameters
token (
InlineCode
) – The token to render.- Return type
-
static
render_line_break
(token)[source] Render a line break in a multiline paragraph.
- Parameters
token
- Return type
-
render_list
(token)[source] Render a markdown list.
- Parameters
token (
List
) – The token to render.- Return type
-
render_list_item
(token)[source] Render a markdown list item.
- Parameters
token (
ListItem
)- Return type
-
render_paragraph
(token)[source] Render a paragraph.
- Parameters
token (
Paragraph
) – The token to render.- Return type
-
-
abort
(message, colour=None)[source] Aborts the program execution.
- Parameters
Changed in version 1.0.1: Added the
colour
option.- Return type
-
braille_spinner
= <itertools.cycle object> Type:
cycle()
itertools.cycle()
of braille characters to use as a loading spinner.New in version 0.7.0.
-
coloured_diff
(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n', removed_colour='\x1b[31m', added_colour='\x1b[32m')[source] Compare two sequences of lines; generate the delta as a unified diff.
Unified diffs are a compact way of showing line changes and a few lines of context. The number of context lines is set by
n
which defaults to three.By default, the diff control lines (those with
---
,+++
, or@@
) are created with a trailing newline. This is helpful so that inputs created fromfile.readlines()
result in diffs that are suitable forfile.writelines()
since both the inputs and outputs have trailing newlines.For inputs that do not have trailing newlines, set the lineterm argument to
''
so that the output will be uniformly newline free.The unidiff format normally has a header for filenames and modification times. Any or all of these may be specified using strings for
fromfile
,tofile
,fromfiledate
, andtofiledate
. The modification times are normally expressed in the ISO 8601 format.New in version 0.3.0.
Example:
>>> for line in coloured_diff( ... 'one two three four'.split(), ... 'zero one tree four'.split(), 'Original', 'Current', ... '2005-01-26 23:30:50', '2010-04-02 10:20:52', ... lineterm='', ... ): ... print(line) --- Original 2005-01-26 23:30:50 +++ Current 2010-04-02 10:20:52 @@ -1,4 +1,4 @@ +zero one -two -three +tree four
- Parameters
fromfile (
str
) – Default''
.tofile (
str
) – Default''
.fromfiledate (
str
) – Default''
.tofiledate (
str
) – Default''
.n (
int
) – Default3
.lineterm (
str
) – Default'\n'
.removed_colour (
Colour
) – TheColour
to use for lines that were removed. Default'\x1b[31m'
.added_colour (
Colour
) – TheColour
to use for lines that were added. Default'\x1b[32m'
.
- Return type
Context manager to hide the cursor for the scope of the
with
block.New in version 0.7.0.
Changed in version 0.9.0: Moved to
consolekit.utils
.- Return type
-
hide_cursor
()[source] Hide the cursor.
To show it again use
show_cursor()
, or use thehidden_cursor()
context manager.New in version 0.7.0.
-
import_commands
(source=None, entry_point=None)[source] Returns a list of all commands.
Commands can be defined locally in the module given in
source
, or by third party extensions who define an entry point in the following format:<name (can be anything)> = <module name>:<command>
-
long_echo
(text, use_pager=None, colour=None)[source] Echo
text
to the terminal, optionally via a pager.New in version 1.2.0.
- Parameters
text (
Union
[str
,StringList
,Iterable
[str
]])use_pager (
Optional
[bool
]) – IfTrue
, forces the use of the pager. IfFalse
the pager is never used. IfNone
the pager is used if sys.stdout` is a TTY and the number of lines is less than the terminal height. DefaultNone
.colour (
Optional
[bool
]) – Whether to use coloured output. Default auto-detect.
Tip
Allow the user to control the value of
use_pager
with theno_pager_option()
decorator.
-
overtype
(*objects, sep=' ', end='', file=None, flush=False)[source] Print
objects
to the text streamfile
, starting with"\r"
, separated bysep
and followed byend
.sep
,end
,file
andflush
, if present, must be given as keyword argumentsAll non-keyword arguments are converted to strings like
str
does and written to the stream, separated by sep and followed by end. If no such arguments are given,overtype()
will just write"\r"
.- Parameters
objects – A list of strings or string-like objects to write to the terminal.
sep (
str
) – String to separate the objects with. Default'␣'
.end (
str
) – String to end with. Default''
.file (
Optional
[IO
]) – An object with awrite(string)
method. Defaultsys.stdout
.flush (
bool
) – IfTrue
, the stream is forcibly flushed. DefaultFalse
.
-
show_cursor
()[source] Show the cursor.
See also
The
hidden_cursor()
context manager.New in version 0.7.0.
-
snake_spinner
= <itertools.cycle object> Type:
cycle()
itertools.cycle()
of braille characters to use as a loading spinner which looks like a snake.New in version 1.1.0.
-
solidus_spinner
= <itertools.cycle object> Type:
cycle()
itertools.cycle()
of characters to use as a loading spinner.New in version 0.7.0.
consolekit.versions
Tool to get software versions.
New in version 1.6.0.
Functions:
|
Return the versions of software dependencies, one per line. |
|
Creates a callback for |
-
get_formatted_versions
(dependencies=(), show_python=True, show_platform=True)[source] Return the versions of software dependencies, one per line.
Overview
consolekit
uses tox to automate testing and packaging,
and pre-commit to maintain code quality.
Install pre-commit
with pip
and install the git hook:
python -m pip install pre-commit
pre-commit install
Coding style
formate is used for code formatting.
It can be run manually via pre-commit
:
pre-commit run formate -a
Or, to run the complete autoformatting suite:
pre-commit run -a
Automated tests
Tests are run with tox
and pytest
.
To run tests for a specific Python version, such as Python 3.6:
tox -e py36
To run tests for all Python versions, simply run:
tox
Build documentation locally
The documentation is powered by Sphinx. A local copy of the documentation can be built with tox
:
tox -e docs
Downloading source code
The consolekit
source code is available on GitHub,
and can be accessed from the following URL: https://github.com/domdfcoding/consolekit
If you have git
installed, you can clone the repository with the following command:
git clone https://github.com/domdfcoding/consolekit
Cloning into 'consolekit'...
remote: Enumerating objects: 47, done.
remote: Counting objects: 100% (47/47), done.
remote: Compressing objects: 100% (41/41), done.
remote: Total 173 (delta 16), reused 17 (delta 6), pack-reused 126
Receiving objects: 100% (173/173), 126.56 KiB | 678.00 KiB/s, done.
Resolving deltas: 100% (66/66), done.

Downloading a ‘zip’ file of the source code
Building from source
The recommended way to build consolekit
is to use tox:
tox -e build
The source and wheel distributions will be in the directory dist
.
If you wish, you may also use pep517.build or another PEP 517-compatible build tool.
License
consolekit
is licensed under the MIT License
A short and simple permissive license with conditions only requiring preservation of copyright and license notices. Licensed works, modifications, and larger works may be distributed under different terms and without source code.
Permissions | Conditions | Limitations |
---|---|---|
|
|
Copyright (c) 2020 Dominic Davis-Foster
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
View the Function Index or browse the Source Code.