admin_console.ainput
index
/usr/lib/python3.10/site-packages/admin_console/ainput.py

ainput.py
Tools for creating a simple text user interfaces in Unix-like systems with using asyncio
Doesn't support Windows or any non-POSIX terminals

 
Modules
       
asyncio
io
os
re
sys
termios
traceback
tty

 
Classes
       
builtins.object
AsyncRawInput
enum.Enum(builtins.object)
colors
logging.Handler(logging.Filterer)
ARILogHandler

 
class ARILogHandler(logging.Handler)
    ARILogHandler(ari: admin_console.ainput.AsyncRawInput, level=0)
 
Custom logging handler for displaying log messages in the terminal.
 
 
Method resolution order:
ARILogHandler
logging.Handler
logging.Filterer
builtins.object

Methods defined here:
__init__(self, ari: admin_console.ainput.AsyncRawInput, level=0)
Initializes the instance - basically setting the formatter to None
and the filter list to empty.
emit(self, record: logging.LogRecord)
Do whatever it takes to actually log the specified logging record.
 
This version is intended to be implemented by subclasses and so
raises a NotImplementedError.

Methods inherited from logging.Handler:
__repr__(self)
Return repr(self).
acquire(self)
Acquire the I/O thread lock.
close(self)
Tidy up any resources used by the handler.
 
This version removes the handler from an internal map of handlers,
_handlers, which is used for handler lookup by name. Subclasses
should ensure that this gets called from overridden close()
methods.
createLock(self)
Acquire a thread lock for serializing access to the underlying I/O.
flush(self)
Ensure all logging output has been flushed.
 
This version does nothing and is intended to be implemented by
subclasses.
format(self, record)
Format the specified record.
 
If a formatter is set, use it. Otherwise, use the default formatter
for the module.
get_name(self)
handle(self, record)
Conditionally emit the specified logging record.
 
Emission depends on filters which may have been added to the handler.
Wrap the actual emission of the record with acquisition/release of
the I/O thread lock. Returns whether the filter passed the record for
emission.
handleError(self, record)
Handle errors which occur during an emit() call.
 
This method should be called from handlers when an exception is
encountered during an emit() call. If raiseExceptions is false,
exceptions get silently ignored. This is what is mostly wanted
for a logging system - most users will not care about errors in
the logging system, they are more interested in application errors.
You could, however, replace this with a custom handler if you wish.
The record which was being processed is passed in to this method.
release(self)
Release the I/O thread lock.
setFormatter(self, fmt)
Set the formatter for this handler.
setLevel(self, level)
Set the logging level of this handler.  level must be an int or a str.
set_name(self, name)

Data descriptors inherited from logging.Handler:
name

Methods inherited from logging.Filterer:
addFilter(self, filter)
Add the specified filter to this handler.
filter(self, record)
Determine if a record is loggable by consulting all the filters.
 
The default is to allow the record to be logged; any filter can veto
this and the record is then dropped. Returns a zero value if a record
is to be dropped, else non-zero.
 
.. versionchanged:: 3.2
 
   Allow filters to be just callables.
removeFilter(self, filter)
Remove the specified filter from this handler.

Data descriptors inherited from logging.Filterer:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
class AsyncRawInput(builtins.object)
    AsyncRawInput(history: list = None, history_limit: int = 30, stdin: _io.TextIOWrapper = <_io.TextIOWrapper name='<stdin>' mode='r' encoding='utf-8'>, stdout: _io.TextIOWrapper = <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, *, loop=None)
 
Main class for asynchronous input and proper output handling
 
Before using its features, self.prepare() should be called
self.end() is called on object destruction handler
 
self.loop : asyncio.BaseEventLoop
    Event loop attached to the IO handler
self.is_reading : bool
    Whether or not the user input is currently receiving
self.stdin : io.TextIOWrapper
    File-like object handling the terminal input
self.stdout : io.TextIOWrapper
    File-like object handling the terminal output
self.read_lastinp : list
    List of str, containing each character for a mutable Unicode string
    Represents an unentered user input displaying on the terminal
self.read_lastprompt : str
    A prompt. Text prepending the user input line.
    To format a prompt, set self.prompt_formats
self.old_tcattrs : list
    List of control terminal arguments that have been set before prepare() called
self.history : list
    List of previous user inputs
self.history_limit : int
    Threshold of automatic entry deletion of old user inputs
self.cursor : int
    Current position of the user terminal cursor.
self.echo : bool = True
    Whether or not the user input is shown on the terminal. Don't modify it manually
self.ctrl_c : (async) function
    Async callback that is called when Ctrl + C is pressed in the terminal
self.keystrokes : dict
    Mapping of keystroke handlers.
    { "raw keystroke code": async callable }
self.prompt_formats : tuple(str, str)
    Formatting header, footer pair for displaying a prompt.
self.input_formats : tuple(str, str)
    Formatting header, footer pair for displaying a user input
 
  Methods defined here:
__del__(self)
__init__(self, history: list = None, history_limit: int = 30, stdin: _io.TextIOWrapper = <_io.TextIOWrapper name='<stdin>' mode='r' encoding='utf-8'>, stdout: _io.TextIOWrapper = <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, *, loop=None)
Parameters
----------
history : list
    List of str containing previous user input
history_limit : int = 30
    Max amount of elements in history list, when exceeded the old values gets deleted.
stdin : io.TextIOWrapper = sys.stdin
    File-like object handling standard input. Should be tty-like file
stdout : io.TextIOWrapper = sys.stdout
    File-like object handling standard output.
add_keystroke(self, keystroke: str, asyncfunction)
Add a new keystroke to the terminal
 
Parameters
----------
keystroke : str
    Raw keystroke code. For example, tab keystroke will be: "\t", Ctrl + F will be "\x06"
asyncfunction : async function
    Async callback called without arguments
end(self)
Disables raw mode, restoring the old TTY settings for standard input
Unhooks the SIGWINCH signal handler.
get_interrupt_handler(self) -> Callable[[Any], Coroutine[Any, Any, Any]]
get_terminal_size(self) -> Union[os.terminal_size, Tuple[int, int]]
move_cursor(self, at: int, *, flush=True, redraw=False)
Moves the cursor across the current line.
Parameter at starts from 1, which means that at=1 is the first character of the terminal line
move_input_cursor(self, at_char: int)
Sets the cursor's input position at specified character. Scrolls the input horizontally when necessary.
on_terminal_resize(self)
prepare(self)
Enables raw mode, saving the old TTY settings. Disables blocking mode for standard input
Hooks up the SIGWINCH signal handler, which will redraw the prompt line if any.
async prompt_keystroke(self, prompt=': ', echo=True) -> str
Start reading a single character from a terminal. Not handling the keystrokes.
 
Parameters
----------
prompt : str
    The text that is displayed before user input
echo : bool
    Whether or not a user input will be displayed.
 
Returns
-------
str
    Resulting pressed keystroke
async prompt_line(self, prompt='> ', echo=True, history_disabled=False, prompt_formats={}, input_formats={})
Start reading a single-line user input with prompt from AsyncRawInput.stdin.
Asynchronous version of input(prompt), handling the keystrokes.
In addition to Python's input(prompt) function, the input is not wrapped
into the new line when overflowed, instead it hides the leftmost characters,
as well as handling the controlling terminal's resizing.
To register a keystroke, use AsyncRawInput.add_keystroke(code, asyncfunction)
 
Parameters
----------
prompt : str
    The text that is displayed before user input
echo : bool
    Whether or not a user input will be displayed. Set to False when prompting a password
history_disabled : bool
    Whether or not a new entry should not be added on successful user input. Set to True when prompting a password
prompt_formats : dict
    Dictionary of text formatting settings that are passed into format_term
    self.prompt_formats = format_term(**prompt_formats)
input_formats : dict
    Dictionary of text formatting settings that are passed into format_term
    self.input_formats = format_term(**input_formats)
redraw_lastinp(self, at: int, force_redraw_prompt=False)
Redisplay a user input at specified position on current cursor line.
If force_redraw_prompt is True, redraws the whole line entirely (including the prompt) regardless of scrolling state
remove_keystroke(self, keystroke: str)
Remove a keystroke from the terminal
 
Parameters : str
    Raw keystroke code.
set_interrupt_handler(self, callback)
Sets the callback for Ctrl + C keystroke
 
Parameters
----------
callback : coroutine or regular function
    (async) callback, called without arguments
write(self, msg: str, **formats)
Write a formatted text to a terminal without CRLF.
Don't use it when a user input is prompted
 
Parameters
----------
msg : str
    The text without CRLF.
**formats : keyword arguments
    Formatting arguments passed as format_term(**formats)
writeln(self, msg: str, **formats)
Show a message on the terminal, preserving a user prompt if any.
 
Parameters
----------
msg : str
    The message text.
**formats : keyword arguments
    Formatting arguments passed as format_term(**formats)

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
class colors(enum.Enum)
    colors(value, names=None, *, module=None, qualname=None, type=None, start=1)
 
ANSI terminal colors
 
 
Method resolution order:
colors
enum.Enum
builtins.object

Data and other attributes defined here:
BLACK = <colors.BLACK: 0>
BLUE = <colors.BLUE: 4>
CYAN = <colors.CYAN: 6>
GREEN = <colors.GREEN: 2>
MAGENTA = <colors.MAGENTA: 5>
RED = <colors.RED: 1>
WHITE = <colors.WHITE: 7>
YELLOW = <colors.YELLOW: 3>

Data descriptors inherited from enum.Enum:
name
The name of the Enum member.
value
The value of the Enum member.

Readonly properties inherited from enum.EnumMeta:
__members__
Returns a mapping of member name->value.
 
This mapping lists all enum members, including aliases. Note that this
is a read-only view of the internal mapping.

 
Functions
       
carriage_return(arg) -> str
Convert plain newline to CR + LF
 
       Returns
       -------
       str
           Converted string
    return arg.replace('
', '
')
format_term(*, bold=False, italic=False, underline=False, blink=False, fgcolor: Union[admin_console.ainput.colors, int] = None, bgcolor: Union[admin_console.ainput.colors, int] = None, **unused) -> (<class 'str'>, <class 'str'>)
Returns a tuple(ansi_escape_start: str, ansi_escape_end: str) for specified format
Tip: "%stext%s" % format_term(args...)
 
Parameters
----------
bold : bool = False
    Formatted text appears bold (on some terminals also appears with bright color)
italic : bool = False
    Formatted text appears italic
underline : bool = False
    Formatted text appears with underline
blink : bool = False
    Formatted text will blink fast if True
fgcolor : colors or int = None
    Set foreground (font) color
    If enum colors specified, formatted text will have an 8-color format
    If integer specified, formatted text will have an 256-color format
bgcolor : colors of int = None
    Set background (fill) color
    If enum colors specified, formatted text will have an 8-color format
    If integer specified, formatted text will have an 256-color format
 
Example
-------
    AsyncRawInput.writeln("%sHello world!%s" % format_term(italic=True, fgcolor=colors.GREEN, bgcolor=colors.BLACK))
rawprint(*args, sep=' ', **kwargs)
Standard print wrapper, but with end='
'
truelen(text: str) -> int
Returns amount of visible-on-terminal characters in the string
truelen_list(seq: Sequence[str]) -> int
Returns amount of visible-on-terminal characters in the sequence of strings

 
Data
        Any = typing.Any
CRITICAL = 50
Callable = typing.Callable
Coroutine = typing.Coroutine
DEBUG = 10
ERROR = 40
INFO = 20
MutableSequence = typing.MutableSequence
NOTSET = 0
Optional = typing.Optional
SIGWINCH = <Signals.SIGWINCH: 28>
Sequence = typing.Sequence
Tuple = typing.Tuple
Union = typing.Union
WARNING = 30
ansi_escape = re.compile('(\\x9B|\\x1B\\[)[0-?]*[ -\\/]*[@-~]')
do_backspace = '\x08\x1b[0K'
next_word = re.compile('\\w+\\W+(\\w+)')
prev_word = re.compile('(\\w+) *$')