asyncutils.console¶
Implementation of an interactive async console base class, as well as an AsyncUtilsConsole class derived from it.
Classes¶
A subclass of |
|
A base class for async consoles. Derives from |
Module Contents¶
- class asyncutils.console.AsyncUtilsConsole(
- loop: asyncio.AbstractEventLoop,
- mod: types.ModuleType = ...,
- modname: str = ...,
- *,
- context_factory: collections.abc.Callable[[], _contextvars.Context] = ...,
Bases:
ConsoleBaseA subclass of
ConsoleBase, used to implement theasyncutilsREPL.loop(required): Event loop used by console interaction.mod: The module to import within the console, determined by the subclass name by default.modname: The name of the above module.context_factory: A function that takes no arguments and returns an instance ofcontextvars.Context, to be used by the event loop.- _interact_hook(ps1: object, kcolor: str, reset: str, fcolor: str) None[source]¶
Called to write code with emulated color (such as import statements to represent the namespace) after the banner has been written, with parameters
ps1representingsys.ps1andkcolor,resetandfcolorrepresenting the ANSI escape codes for the keyword color, color reset and the function color respectively.
- showtraceback() None[source]¶
Display the formatted traceback of the exception being handled. If there was no exception, do nothing.
Note
This differs from the superclass behaviour, where
AttributeErroris raised outright.
- write_special(msg: str) None[source]¶
Writes
msgto stderr if and only if the quiet flag is not set.
- property is_running: bool¶
Performs internal state consistency checks and returns whether the console is currently running. Only one
AsyncUtilsConsolecan be running at a time.
- class asyncutils.console.ConsoleBase(
- loop: asyncio.AbstractEventLoop,
- mod: types.ModuleType = ...,
- modname: str = ...,
- *,
- context_factory: collections.abc.Callable[[], _contextvars.Context] = ...,
Bases:
code.InteractiveConsole,abc.ABCA base class for async consoles. Derives from
InteractiveConsole, orInteractiveColoredConsoleif available. It is inspired byasyncio.__main__and highly adaptable.loop(required): Event loop used by console interaction.mod: The module to import within the console, determined by the subclass name by default.modname: The name of the above module.context_factory: A function that takes no arguments and returns an instance ofcontextvars.Context, to be used by the event loop.- __callback(
- fut: concurrent.futures.Future[Any],
- code: types.CodeType,
- /,
- *,
- makef: collections.abc.Callable[[types.CodeType, dict[str, Any]], collections.abc.Callable[[], Any]] = ...,
- corocheck: collections.abc.Callable[[object], TypeGuard[collections.abc.Coroutine[Any, Any, Any]]] = ...,
- futchain: collections.abc.Callable[[asyncio.Task[Any], concurrent.futures.Future[Any]], object] = ...,
Called by runcode internally. To change its behaviour, override the entire method in a subclass with different default parameters.
- classmethod __init_subclass__(
- *,
- name: str = ...,
- version: str = ...,
- description: str = ...,
- default_local_exit: bool = ...,
- disallow_subclass_msg: str | None = ...,
- native_handler: collections.abc.Callable[[dict[str, Any]], object] | None = ...,
- other_handlers: dict[str, collections.abc.Callable[[dict[str, Any]], object] | None] = ...,
- additional_interrupt_hooks: collections.abc.Iterable[collections.abc.Callable[[Self], object]] = ...,
- additional_memerr_hooks: collections.abc.Iterable[collections.abc.Callable[[Self], object]] = ...,
- template: str = ...,
- **k: object,
- All of the arguments below are optional.
name: name of the module using the consoleversion: version of the module using the consoledescription: description of the module using the consoledefault_local_exit,disallow_subclass_msg,native_handler,other_handlers,additional_interrupt_hooks,additional_memerr_hooks: see abovetemplate: the console banner to use, with %-placeholders for name, version and descriptionAdditional keyword arguments are used tosubstitute %-placeholders in template.
- _interact_hook(ps1: object, kcolor: str, reset: str, fcolor: str) None[source]¶
Called to write code with emulated color (such as import statements to represent the namespace) after the banner has been written, with parameters
ps1representingsys.ps1andkcolor,resetandfcolorrepresenting the ANSI escape codes for the keyword color, color reset and the function color respectively.
- interact(banner: str | None = ..., *, ps1: object = ...) None[source]¶
In the main thread, the run method is preferred.
- interrupt() None[source]¶
Pass
additional_interrupt_hooksto the subclass constructor to change the behaviour when encountering aKeyboardInterrupt, instead of touching this method.
- memoryerror() None[source]¶
Pass
additional_memerr_hooksto the subclass constructor to change the behaviour when encountering aMemoryError, instead of touching this method.
- posthook() None[source]¶
- Called by
run()after the interaction has ended before writing the exit message. Should not raise errors.It is highly recommended that subclasses implement this and callsuper().posthook()within the implementation after the custom logic.
- abstractmethod prehook(max_memerrs: int | None) None[source]¶
- Called by
run()before beginning the interaction logic. Can raise errors.When implementing, callsuper().prehook(max_memerrs)before everything. This allows subclasses to pass their own value ofmax_memerrs.
- refresh() None[source]¶
Callback in
interrupt()andmemoryerror().
- run(
- *,
- exitmsg: str = ...,
- threadname: str = ...,
- max_memerrs: int = ...,
- always_run_interactive: bool = ...,
- always_install_completer: bool = ...,
- suppress_asyncio_warnings: bool = ...,
- suppress_unawaited_coroutine_warnings: bool = ...,
- Run the console and return the integer return code.The strings
exitmsgandthreadnameshould support%-formatting, the placeholder being the module name.Pass a negative value formax_memerrsto disable the stop after certain number ofMemoryError’s behaviour.Ifalways_install_completeris True, set the completer on readline as long as readline is available.PassTrueforsuppress_asyncio_warningsandsuppress_unawaited_coroutine_warningsto silence asyncio logging and warnings for garbage-collected coroutines not being awaited respectively.If you wish the console to act like a console even when stdin is piped, passalways_run_interactive=Trueor start Python with the-iflag.
- runcode(
- code: types.CodeType,
- *,
- futimpl: collections.abc.Callable[[], concurrent.futures.Future[Any]] = ...,
- dont_show_traceback: tuple[asyncutils._internal.types.ExcType, Ellipsis] = ...,
- threadsafe: bool = ...,
- Run
code, an instance oftypes.CodeType.futimplis a function that returns an instance ofconcurrent.futures.Future.dont_show_tracebackis a tuple of types of exceptions for which the traceback should not be shown if they are to occur.threadsafedictates whether to run the code in the event loop usingcall_soon_threadsafe()instead ofcall_soon().
- set_return_code(exc: SystemExit, /) None[source]¶
- set_return_code(code: int | str, /) None
Set the return code of this console from an instance of
SystemExitor an integer return code and exit the console.
- showtraceback() None[source]¶
Display the formatted traceback of the exception being handled. If there was no exception, do nothing.
Note
This differs from the superclass behaviour, where
AttributeErroris raised outright.
- write_special(msg: str) None[source]¶
Called to write the banner and exit messages. Can have a different implementation than
write().
- BANNER: ClassVar[str]¶
A %-formattable string representating the template of the banner to be shown when the console starts.
- LOCALS_HANDLERS: ClassVar[collections.ChainMap[str, collections.abc.Callable[[dict[str, Any]], Any] | None]]¶
- module name -> (locals of console of corresponding type -> Any)Add handlers for the module of your own console with
native_handlerand other modules withother_handlers.
- NAME: ClassVar[str]¶
The name of the module implementing this console, detected from the class name if the keyword argument
nameis not provided to the subclass constructor.
- property _internal_is_running: bool¶
Whether the console thinks itself is running. Can be used in
is_runningfor state consistency checks.
- property context: _contextvars.Context¶
The
contextvars.Contextinstance passed to methods of the underlyingasyncioevent loop.
- default_local_exit: ClassVar[bool]¶
Whether Python should continue running after the console exits by default, as opposed to the console raising
SystemExitdirectly.
- disallow_subclass_msg: ClassVar[str]¶
The error message when attempts are made to subclass subclasses of this class. Specified through the
disallow_subclass_msgargument, which any unsubclassable console should pass.
- property exc: SystemExit | None¶
The
SystemExitinstance that caused the console to exit, orNoneif the console has not exited.
- interrupt_hooks: ClassVar[tuple[collections.abc.Callable[[Self], Any], Ellipsis]]¶
Functions called when
KeyboardInterruptoccurs, in that order, besides essential hardcoded logic.Note
Add hooks using the
additional_interrupt_hooksclass construction parameter.
- property is_running: bool¶
Whether the console is running. The default implementation simply returns
_internal_is_running.
- memerr_hooks: ClassVar[tuple[collections.abc.Callable[[Self], Any], Ellipsis]]¶
Functions called when a
MemoryErroroccurs, in that order, besides essential hardcoded logic.Note
Add hooks using the
additional_memerr_hooksclass construction parameter.
- property memory_errors: int¶
The number of
MemoryError’s that have occurred.