pyTooling.TerminalUI

A set of helpers to implement a text user interface (TUI) in a terminal.

Classes

  • TerminalBaseApplication: The class offers a basic terminal application base-class.

  • Severity: Logging message severity levels.

  • Mode: Create a collection of name/value pairs.

  • Line: Represents a single message line with a severity and indentation level.

  • ILineTerminal: A mixin class (interface) to provide class-local terminal writing methods.

  • TerminalApplication: The class offers a basic terminal application base-class.


Classes

class pyTooling.TerminalUI.TerminalBaseApplication[source]

The class offers a basic terminal application base-class.

It offers basic colored output via colorama as well as retrieving the terminal’s width.

Inheritance

Inheritance diagram of TerminalBaseApplication

NOT_IMPLEMENTED_EXCEPTION_EXIT_CODE: ClassVar[int] = 240

Return code, if unimplemented methods or code sections were called.

UNHANDLED_EXCEPTION_EXIT_CODE: ClassVar[int] = 241

Return code, if an unhandled exception reached the topmost exception handler.

PYTHON_VERSION_CHECK_FAILED_EXIT_CODE: ClassVar[int] = 254

Return code, if version check was not successful.

FATAL_EXIT_CODE: ClassVar[int] = 255

Return code for fatal exits.

ISSUE_TRACKER_URL: ClassVar[str] = None

URL to the issue tracker for reporting bugs.

INDENT: ClassVar[str] = '  '

Indentation. Default: "  " (2 spaces)

Foreground = {'BLUE': '\x1b[94m', 'CYAN': '\x1b[96m', 'DARK_BLUE': '\x1b[34m', 'DARK_CYAN': '\x1b[36m', 'DARK_GRAY': '\x1b[90m', 'DARK_GREEN': '\x1b[32m', 'DARK_RED': '\x1b[31m', 'DARK_YELLOW': '\x1b[33m', 'ERROR': '\x1b[91m', 'GRAY': '\x1b[37m', 'GREEN': '\x1b[92m', 'HEADLINE': '\x1b[95m', 'MAGENTA': '\x1b[95m', 'NOCOLOR': '\x1b[39m', 'RED': '\x1b[91m', 'WARNING': '\x1b[93m', 'WHITE': '\x1b[97m', 'YELLOW': '\x1b[93m'}

Terminal colors

__init__()[source]

Initialize a terminal.

If the Python package colorama [1] is available, then initialize it for colored outputs.

Return type:

None

_stdin: TextIOWrapper

STDIN

_stdout: TextIOWrapper

STDOUT

_stderr: TextIOWrapper

STDERR

_width: int

Terminal width in characters

_height: int

Terminal height in characters

InitializeColors()[source]

Initialize the terminal for color support by colorama.

Return type:

bool

Returns:

True, if ‘colorama’ package could be imported and initialized.

UninitializeColors()[source]

Uninitialize the terminal for color support by colorama.

Return type:

bool

Returns:

True, if ‘colorama’ package could be imported and uninitialized.

property Width: int

Returns the current terminal window’s width.

property Height: int

Returns the current terminal window’s height.

static GetTerminalSize()[source]

Returns the terminal size as tuple (width, height) for Windows, macOS (Darwin), Linux, cygwin (Windows), MinGW32/64 (Windows).

Return type:

Tuple[int, int]

Returns:

A tuple containing width and height of the terminal’s size in characters.

Raises:

PlatformNotSupportedException – When a platform is not yet supported.

__GetTerminalSizeOnWindows()

Returns the current terminal window’s size for Windows.

kernel32.dll:GetConsoleScreenBufferInfo() is used to retrieve the information.

Return type:

Tuple[int, int]

Returns:

A tuple containing width and height of the terminal’s size in characters.

__GetTerminalSizeOnLinux()

Returns the current terminal window’s size for Linux.

ioctl(TIOCGWINSZ) is used to retrieve the information. As a fallback, environment variables COLUMNS and LINES are checked.

Return type:

Optional[Tuple[int, int]]

Returns:

A tuple containing width and height of the terminal’s size in characters.

WriteToStdOut(message)[source]

Low-level method for writing to STDOUT.

Parameters:

message (str) – Message to write to STDOUT.

Return type:

int

Returns:

Number of written characters.

WriteLineToStdOut(message, end='\\n')[source]

Low-level method for writing to STDOUT.

Parameters:
  • message (str :param message: Message to write to STDOUT.)

  • end (str :param end: Use newline character. Default: ``)

Return type:

int

``.
return:

Number of written characters.

Return type:

int

Parameters:
WriteToStdErr(message)[source]

Low-level method for writing to STDERR.

Parameters:

message (str) – Message to write to STDERR.

Return type:

int

Returns:

Number of written characters.

WriteLineToStdErr(message, end='\\n')[source]

Low-level method for writing to STDERR.

Parameters:
  • message (str :param message: Message to write to STDERR.)

  • end (str :param end: Use newline character. Default: ``)

Return type:

int

``.
return:

Number of written characters.

Return type:

int

Parameters:
FatalExit(returnCode=0)[source]

Exit the terminal application by uninitializing color support and returning a fatal Exit code.

Return type:

NoReturn

Parameters:

returnCode (int)

Exit(returnCode=0)[source]

Exit the terminal application by uninitializing color support and returning an Exit code.

Return type:

NoReturn

Parameters:

returnCode (int)

CheckPythonVersion(version)[source]

Check if the used Python interpreter fulfills the minimum version requirements.

Return type:

None

PrintException(ex)[source]

Prints an exception of type Exception and its traceback.

If the exception as a nested action, the cause is printed as well.

If ISSUE_TRACKER_URL is configured, a URL to the issue tracker is added.

Return type:

NoReturn

Parameters:

ex (Exception)

PrintNotImplementedError(ex)[source]

Prints a not-implemented exception of type NotImplementedError.

Return type:

NoReturn

Parameters:

ex (NotImplementedError)

PrintExceptionBase(ex)[source]

Prints an exception of type ExceptionBase and its traceback.

If the exception as a nested action, the cause is printed as well.

If ISSUE_TRACKER_URL is configured, a URL to the issue tracker is added.

Return type:

NoReturn

Parameters:

ex (Exception)

class property HasClassAttributes: bool

Check if class has Attributes.

Returns:

True, if the class has Attributes.

class property HasMethodAttributes: bool

Check if class has any method with Attributes.

Returns:

True, if the class has any method with Attributes.

class pyTooling.TerminalUI.Severity(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Logging message severity levels.

Inheritance

Inheritance diagram of Severity

Fatal = 100

Fatal messages

Error = 70

Error messages

Quiet = 60

Always visible messages, even in quiet mode.

Warning = 50

Warning messages

Info = 20

Informative messages

Normal = 10

Normal messages

DryRun = 8

Messages visible in a dry-run

Verbose = 5

Verbose messages

Debug = 2

Debug messages

All = 0

All messages

__hash__()[source]

Return hash(self).

__eq__(other)[source]

Compare two Severity instances (severity level) for equality.

Parameters:

other (Any) – Parameter to compare against.

Return type:

bool

Returns:

True, if both severity levels are equal.

Raises:

TypeError – If parameter other is not of type Severity.

__ne__(other)[source]

Compare two Severity instances (severity level) for inequality.

Parameters:

other (Any) – Parameter to compare against.

Return type:

bool

Returns:

True, if both severity levels are unequal.

Raises:

TypeError – If parameter other is not of type Severity.

__lt__(other)[source]

Compare two Severity instances (severity level) for less-than.

Parameters:

other (Any) – Parameter to compare against.

Return type:

bool

Returns:

True, if severity levels is less than other severity level.

Raises:

TypeError – If parameter other is not of type Severity.

__le__(other)[source]

Compare two Severity instances (severity level) for less-than-or-equal.

Parameters:

other (Any) – Parameter to compare against.

Return type:

bool

Returns:

True, if severity levels is less than or equal other severity level.

Raises:

TypeError – If parameter other is not of type Severity.

__gt__(other)[source]

Compare two Severity instances (severity level) for greater-than.

Parameters:

other (Any) – Parameter to compare against.

Return type:

bool

Returns:

True, if severity levels is greater than other severity level.

Raises:

TypeError – If parameter other is not of type Severity.

__ge__(other)[source]

Compare two Severity instances (severity level) for greater-than-or-equal.

Parameters:

other (Any) – Parameter to compare against.

Return type:

bool

Returns:

True, if severity levels is greater than or equal other severity level.

Raises:

TypeError – If parameter other is not of type Severity.

class pyTooling.TerminalUI.Mode(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Inheritance

Inheritance diagram of Mode

class pyTooling.TerminalUI.Line(message, severity=Severity.Normal, indent=0, appendLinebreak=True)[source]

Represents a single message line with a severity and indentation level.

Inheritance

Inheritance diagram of Line

Parameters:
_LOG_MESSAGE_FORMAT__ = {Severity.Debug: 'DEBUG: {message}', Severity.Verbose: 'VERBOSE: {message}', Severity.DryRun: 'DRYRUN: {message}', Severity.Normal: '{message}', Severity.Info: 'INFO: {message}', Severity.Warning: 'WARNING: {message}', Severity.Quiet: '{message}', Severity.Error: 'ERROR: {message}', Severity.Fatal: 'FATAL: {message}'}

Message line formatting rules.

__init__(message, severity=Severity.Normal, indent=0, appendLinebreak=True)[source]

Constructor for a new Line object.

Parameters:
Return type:

None

property Message: str

Return the indented line.

Returns:

Raw message of the line.

property Severity: Severity

Return the line’s severity level.

Returns:

Severity level of the message line.

property Indent: int

Return the line’s indentation level.

Returns:

Indentation level.

IndentBy(indent)[source]

Increase a line’s indentation level.

Parameters:

indent (int) – Indentation level added to the current indentation level.

Return type:

int

property AppendLinebreak: bool

Returns if a linebreak should be added at the end of the message.

Returns:

True, if a linebreak should be added.

__str__()[source]

Returns a formatted version of a Line objects as a string.

Return type:

str

class property HasClassAttributes: bool

Check if class has Attributes.

Returns:

True, if the class has Attributes.

class property HasMethodAttributes: bool

Check if class has any method with Attributes.

Returns:

True, if the class has any method with Attributes.

class pyTooling.TerminalUI.ILineTerminal(terminal=None)[source]

A mixin class (interface) to provide class-local terminal writing methods.

Inheritance

Inheritance diagram of ILineTerminal

Parameters:

terminal (TerminalBaseApplication | None)

__init__(terminal=None)[source]

MixIn initializer.

Parameters:

terminal (TerminalBaseApplication | None)

Return type:

None

property Terminal: TerminalBaseApplication

Return the local terminal instance.

WriteLine(line, condition=True)[source]

Write an entry to the local terminal.

Return type:

bool

Parameters:
WriteFatal(*args, condition=True, **kwargs)[source]

Write a fatal message if condition is true.

Return type:

bool

Parameters:
WriteError(*args, condition=True, **kwargs)[source]

Write an error message if condition is true.

Return type:

bool

Parameters:
WriteWarning(*args, condition=True, **kwargs)[source]

Write a warning message if condition is true.

Return type:

bool

Parameters:
WriteInfo(*args, condition=True, **kwargs)[source]

Write an info message if condition is true.

Return type:

bool

Parameters:
WriteQuiet(*args, condition=True, **kwargs)[source]

Write a message even in quiet mode if condition is true.

Return type:

bool

Parameters:
WriteNormal(*args, condition=True, **kwargs)[source]

Write a normal message if condition is true.

Return type:

bool

Parameters:
WriteVerbose(*args, condition=True, **kwargs)[source]

Write a verbose message if condition is true.

Return type:

bool

Parameters:
WriteDebug(*args, condition=True, **kwargs)[source]

Write a debug message if condition is true.

Return type:

bool

Parameters:
WriteDryRun(*args, condition=True, **kwargs)[source]

Write a dry-run message if condition is true.

Return type:

bool

Parameters:
class property HasClassAttributes: bool

Check if class has Attributes.

Returns:

True, if the class has Attributes.

class property HasMethodAttributes: bool

Check if class has any method with Attributes.

Returns:

True, if the class has any method with Attributes.

class pyTooling.TerminalUI.TerminalApplication(mode=Mode.AllLinearToStdOut)[source]

Inheritance

Inheritance diagram of TerminalApplication

_LOG_MESSAGE_FORMAT__ = {Severity.Debug: '{DARK_GRAY}{message}{NOCOLOR}', Severity.Verbose: '{GRAY}{message}{NOCOLOR}', Severity.DryRun: '{DARK_CYAN}[DRY] {message}{NOCOLOR}', Severity.Normal: '{WHITE}{message}{NOCOLOR}', Severity.Info: '{WHITE}{message}{NOCOLOR}', Severity.Warning: '{YELLOW}[WARNING] {message}{NOCOLOR}', Severity.Quiet: '{WHITE}{message}{NOCOLOR}', Severity.Error: '{RED}[ERROR]   {message}{NOCOLOR}', Severity.Fatal: '{DARK_RED}[FATAL]   {message}{NOCOLOR}'}

Message formatting rules.

__init__(mode=Mode.AllLinearToStdOut)[source]

Initializer of a line based terminal interface.

Parameters:

mode (Mode)

Return type:

None

_LOG_LEVEL_ROUTING__: Dict[Severity, Tuple[Callable[[str, str], int]]]

Message routing rules.

CheckPythonVersion(version)

Check if the used Python interpreter fulfills the minimum version requirements.

Return type:

None

Exit(returnCode=0)

Exit the terminal application by uninitializing color support and returning an Exit code.

Return type:

NoReturn

Parameters:

returnCode (int)

FATAL_EXIT_CODE: ClassVar[int] = 255

Return code for fatal exits.

FatalExit(returnCode=0)

Exit the terminal application by uninitializing color support and returning a fatal Exit code.

Return type:

NoReturn

Parameters:

returnCode (int)

Foreground = {'BLUE': '\x1b[94m', 'CYAN': '\x1b[96m', 'DARK_BLUE': '\x1b[34m', 'DARK_CYAN': '\x1b[36m', 'DARK_GRAY': '\x1b[90m', 'DARK_GREEN': '\x1b[32m', 'DARK_RED': '\x1b[31m', 'DARK_YELLOW': '\x1b[33m', 'ERROR': '\x1b[91m', 'GRAY': '\x1b[37m', 'GREEN': '\x1b[92m', 'HEADLINE': '\x1b[95m', 'MAGENTA': '\x1b[95m', 'NOCOLOR': '\x1b[39m', 'RED': '\x1b[91m', 'WARNING': '\x1b[93m', 'WHITE': '\x1b[97m', 'YELLOW': '\x1b[93m'}

Terminal colors

static GetTerminalSize()

Returns the terminal size as tuple (width, height) for Windows, macOS (Darwin), Linux, cygwin (Windows), MinGW32/64 (Windows).

Return type:

Tuple[int, int]

Returns:

A tuple containing width and height of the terminal’s size in characters.

Raises:

PlatformNotSupportedException – When a platform is not yet supported.

class property HasClassAttributes: bool

Check if class has Attributes.

Returns:

True, if the class has Attributes.

class property HasMethodAttributes: bool

Check if class has any method with Attributes.

Returns:

True, if the class has any method with Attributes.

property Height: int

Returns the current terminal window’s height.

INDENT: ClassVar[str] = '  '

Indentation. Default: "  " (2 spaces)

ISSUE_TRACKER_URL: ClassVar[str] = None

URL to the issue tracker for reporting bugs.

InitializeColors()

Initialize the terminal for color support by colorama.

Return type:

bool

Returns:

True, if ‘colorama’ package could be imported and initialized.

NOT_IMPLEMENTED_EXCEPTION_EXIT_CODE: ClassVar[int] = 240

Return code, if unimplemented methods or code sections were called.

PYTHON_VERSION_CHECK_FAILED_EXIT_CODE: ClassVar[int] = 254

Return code, if version check was not successful.

PrintException(ex)

Prints an exception of type Exception and its traceback.

If the exception as a nested action, the cause is printed as well.

If ISSUE_TRACKER_URL is configured, a URL to the issue tracker is added.

Return type:

NoReturn

Parameters:

ex (Exception)

PrintExceptionBase(ex)

Prints an exception of type ExceptionBase and its traceback.

If the exception as a nested action, the cause is printed as well.

If ISSUE_TRACKER_URL is configured, a URL to the issue tracker is added.

Return type:

NoReturn

Parameters:

ex (Exception)

PrintNotImplementedError(ex)

Prints a not-implemented exception of type NotImplementedError.

Return type:

NoReturn

Parameters:

ex (NotImplementedError)

UNHANDLED_EXCEPTION_EXIT_CODE: ClassVar[int] = 241

Return code, if an unhandled exception reached the topmost exception handler.

UninitializeColors()

Uninitialize the terminal for color support by colorama.

Return type:

bool

Returns:

True, if ‘colorama’ package could be imported and uninitialized.

property Verbose: bool

Returns true, if verbose messages are enabled.

property Width: int

Returns the current terminal window’s width.

WriteLineToStdErr(message, end='\\n')

Low-level method for writing to STDERR.

Parameters:
  • message (str :param message: Message to write to STDERR.)

  • end (str :param end: Use newline character. Default: ``)

Return type:

int

``.
return:

Number of written characters.

Return type:

int

Parameters:
WriteLineToStdOut(message, end='\\n')

Low-level method for writing to STDOUT.

Parameters:
  • message (str :param message: Message to write to STDOUT.)

  • end (str :param end: Use newline character. Default: ``)

Return type:

int

``.
return:

Number of written characters.

Return type:

int

Parameters:
WriteToStdErr(message)

Low-level method for writing to STDERR.

Parameters:

message (str) – Message to write to STDERR.

Return type:

int

Returns:

Number of written characters.

WriteToStdOut(message)

Low-level method for writing to STDOUT.

Parameters:

message (str) – Message to write to STDOUT.

Return type:

int

Returns:

Number of written characters.

_height: int

Terminal height in characters

_stderr: TextIOWrapper

STDERR

_stdin: TextIOWrapper

STDIN

_stdout: TextIOWrapper

STDOUT

_width: int

Terminal width in characters

property Debug: bool

Returns true, if debug messages are enabled.

property Quiet: bool

Returns true, if quiet mode is enabled.

property LogLevel: Severity

Return the current minimal severity level for writing.

ExitOnPreviousErrors()[source]

Exit application if errors have been printed.

Return type:

None

ExitOnPreviousWarnings()[source]

Exit application if warnings have been printed.

Return type:

None

WriteLine(line)[source]

Print a formatted line to the underlying terminal/console offered by the operating system.

Return type:

bool

Parameters:

line (Line)

WriteNormal(message, indent=0, appendLinebreak=True)[source]

Write a normal message.

Depending on internal settings and rules, a message might be skipped.

Parameters:
  • message (str) – Message to write.

  • indent (int) – Indentation level of the message.

  • appendLinebreak (bool) – Append a linebreak after the message. Default: True

Return type:

bool

Returns:

True, if message was actually written.