Improved console

This commit is contained in:
Sven Heidemann 2020-12-15 14:03:31 +01:00
parent 096b50f9f1
commit 7473b8deab
4 changed files with 108 additions and 33 deletions

View File

@ -1,3 +1,4 @@
import atexit
from datetime import datetime from datetime import datetime
from sh_edraft.configuration.configuration import Configuration from sh_edraft.configuration.configuration import Configuration
@ -7,6 +8,7 @@ from sh_edraft.hosting.application_runtime import ApplicationRuntime
from sh_edraft.hosting.base.application_host_base import ApplicationHostBase from sh_edraft.hosting.base.application_host_base import ApplicationHostBase
from sh_edraft.service.providing.service_provider import ServiceProvider from sh_edraft.service.providing.service_provider import ServiceProvider
from sh_edraft.service.providing.base.service_provider_base import ServiceProviderBase from sh_edraft.service.providing.base.service_provider_base import ServiceProviderBase
from sh_edraft.utils.console import Console
class ApplicationHost(ApplicationHostBase): class ApplicationHost(ApplicationHostBase):
@ -27,6 +29,8 @@ class ApplicationHost(ApplicationHostBase):
self._start_time: datetime = datetime.now() self._start_time: datetime = datetime.now()
self._end_time: datetime = datetime.now() self._end_time: datetime = datetime.now()
atexit.register(Console.close)
@property @property
def configuration(self) -> ConfigurationBase: def configuration(self) -> ConfigurationBase:
return self._config return self._config

View File

@ -1,6 +1,8 @@
import contextlib
import io
import os import os
import subprocess import sys
from typing import Union from typing import Union, Optional
from termcolor import colored from termcolor import colored
from sh_edraft.utils.console.model.background_color import BackgroundColor from sh_edraft.utils.console.model.background_color import BackgroundColor
@ -10,14 +12,26 @@ from sh_edraft.utils.console.model.foreground_color import ForegroundColor
class Console: class Console:
_background_color: BackgroundColor = BackgroundColor.default _background_color: BackgroundColor = BackgroundColor.default
_foreground_color: ForegroundColor = ForegroundColor.default _foreground_color: ForegroundColor = ForegroundColor.default
_x: Optional[int] = None
_y: Optional[int] = None
@property """
def background_color(self) -> BackgroundColor: Properties
return self._background_color """
@classmethod
@property @property
def foreground_color(self) -> ForegroundColor: def background_color(cls) -> str:
return self._foreground_color return str(cls._background_color.value)
@classmethod
@property
def foreground_color(cls) -> str:
return str(cls._foreground_color.value)
"""
Settings
"""
@classmethod @classmethod
def set_background_color(cls, color: Union[BackgroundColor, str]): def set_background_color(cls, color: Union[BackgroundColor, str]):
@ -33,18 +47,54 @@ class Console:
else: else:
cls._foreground_color = color cls._foreground_color = color
# useful methods @classmethod
def reset_cursor_position(cls):
cls._x = None
cls._y = None
@classmethod
def set_cursor_position(cls, x: int, y: int):
cls._x = x
cls._y = y
"""
Useful protected methods
"""
@classmethod
def _output(cls, string: str, x: int = None, y: int = None, end='\n'):
args = []
colored_args = []
if x is not None and y is not None:
args.append(f'\033[{x};{y}H')
elif cls._x is not None and cls._y is not None:
args.append(f'\033[{cls._x};{cls._y}H')
colored_args.append(string)
if cls._foreground_color != ForegroundColor.default and cls._background_color == BackgroundColor.default:
colored_args.append(cls._foreground_color.value)
elif cls._foreground_color == ForegroundColor.default and cls._background_color != BackgroundColor.default:
colored_args.append(cls._background_color.value)
elif cls._foreground_color != ForegroundColor.default and cls._background_color != BackgroundColor.default:
colored_args.append(cls._foreground_color.value)
colored_args.append(cls._background_color.value)
args.append(colored(*colored_args))
print(*args, end=end)
"""
Useful public methods
"""
@staticmethod @staticmethod
def clear(): def clear():
os.system('cls' if os.name == 'nt' else 'clear') os.system('cls' if os.name == 'nt' else 'clear')
@staticmethod @staticmethod
def new(): def close():
if os.name == 'nt': Console.read_line('\nPress any key to continue...')
os.system("start /wait cmd") exit()
else:
p = subprocess.Popen(args=["gnome-terminal"])
p.communicate()
@staticmethod @staticmethod
def read(output: str = None) -> str: def read(output: str = None) -> str:
@ -61,16 +111,21 @@ class Console:
cls._foreground_color = ForegroundColor.default cls._foreground_color = ForegroundColor.default
@classmethod @classmethod
def write(cls, string: str): def write(cls, *args):
if cls._foreground_color == ForegroundColor.default: string = ' '.join(map(str, args))
print(colored(string), end='') cls._output(string, end='')
else:
print(colored(string, cls._foreground_color.value), end='') @classmethod
def write_at(cls, x: int, y: int, *args):
string = ' '.join(map(str, args))
cls._output(string, x, y)
@classmethod @classmethod
def write_line(cls, *args): def write_line(cls, *args):
string = ' '.join(map(str, args)) string = ' '.join(map(str, args))
if cls._foreground_color == ForegroundColor.default: cls._output(string)
print(colored(string))
else: @classmethod
print(colored(string, cls._foreground_color.value)) def write_line_at(cls, x: int, y: int, *args):
string = ' '.join(map(str, args))
cls._output(string, x, y)

View File

@ -3,12 +3,12 @@ from enum import Enum
class BackgroundColor(Enum): class BackgroundColor(Enum):
default = 'default' default = 'on_default'
grey = 'grey' grey = 'on_grey'
red = 'red' red = 'on_red'
green = 'green' green = 'on_green'
yellow = 'yellow' yellow = 'on_yellow'
blue = 'blue' blue = 'on_blue'
magenta = 'magenta' magenta = 'on_magenta'
cyan = 'cyan' cyan = 'on_cyan'
white = 'white' white = 'on_white'

View File

@ -8,7 +8,7 @@ from sh_edraft.hosting.base import ApplicationBase
from sh_edraft.logging import Logger from sh_edraft.logging import Logger
from sh_edraft.logging.base import LoggerBase from sh_edraft.logging.base import LoggerBase
from sh_edraft.service.providing.base import ServiceProviderBase from sh_edraft.service.providing.base import ServiceProviderBase
from sh_edraft.utils import CredentialManager from sh_edraft.utils import CredentialManager, Console
from tests_dev.db.user_repo import UserRepo from tests_dev.db.user_repo import UserRepo
from tests_dev.db.user_repo_base import UserRepoBase from tests_dev.db.user_repo_base import UserRepoBase
@ -56,3 +56,19 @@ class Program(ApplicationBase):
self._logger.debug(__name__, f'Environment: {self._configuration.environment.environment_name}') self._logger.debug(__name__, f'Environment: {self._configuration.environment.environment_name}')
self._logger.debug(__name__, f'Customer: {self._configuration.environment.customer}') self._logger.debug(__name__, f'Customer: {self._configuration.environment.customer}')
self._services.get_service(UserRepoBase).add_test_user() self._services.get_service(UserRepoBase).add_test_user()
Console.clear()
Console.write_line('Hello', 'World')
# name = Console.read_line('Name: ')
# Console.write_line('Hello', name)
Console.set_foreground_color('red')
Console.set_background_color('green')
Console.set_cursor_position(5, 5)
Console.write_line('Error')
Console.write_line_at(10, 10, 'Error')
Console.reset_cursor_position()
Console.set_foreground_color('green')
Console.set_background_color('default')
Console.write('Test')
Console.write_line('1')
Console.write_line(Console.foreground_color)