This commit is contained in:
santaspeen 2022-02-20 23:23:30 +03:00
parent 931be6aa5e
commit 363a23dd70
5 changed files with 79 additions and 27 deletions

View File

@ -1,16 +1,26 @@
# CLI in Python # CLI in Python
#### Версия для русских: [здесь](./README_RU.md)
## Консольная оболочка для программ на питоне ## Консольная оболочка для программ на питоне
### О проекте ### About
1. Он не выложен 1.
### Usage
## Ссылки ```python
from console import Console
* [Мой Telegram](https://t.me/SantaSpeen "SantaSpeen"): https://t.me/SantaSpeen cli = Console(prompt_in=">", prompt_out="]:")
Используемые библиотеки: ```
* ## Links
* [Author's Telegram](https://t.me/SantaSpeen "SantaSpeen"): https://t.me/SantaSpeen
Used in:
* [Python-CLI-Game-Engine](https://github.com/SantaSpeen/Python-CLI-Game-Engine)

24
README_RU.md Normal file
View File

@ -0,0 +1,24 @@
# CLI in Python
## Консольная оболочка для программ на питоне
### О проекте
1.
### Использование
```python
from console import Console
cli = Console(prompt_in=">", prompt_out="]:")
```
## Ссылки
* [Мой Telegram](https://t.me/SantaSpeen "SantaSpeen"): https://t.me/SantaSpeen
Используемые в поектах:
* [Python-CLI-Game-Engine](https://github.com/SantaSpeen/Python-CLI-Game-Engine)

View File

@ -2,6 +2,7 @@
# Developed by Ahegao Devs # Developed by Ahegao Devs
# Written by: SantaSpeen # Written by: SantaSpeen
# Version 1.0
# Licence: MIT # Licence: MIT
# (c) ahegao.ovh 2022 # (c) ahegao.ovh 2022
@ -34,7 +35,7 @@ class Console:
prompt_in: str = ">", prompt_in: str = ">",
prompt_out: str = "]:", prompt_out: str = "]:",
not_found: str = "Command \"%s\" not found in alias.", not_found: str = "Command \"%s\" not found in alias.",
file: str or None = None, file: str or None = ConsoleIO,
debug: bool = False) -> None: debug: bool = False) -> None:
""" """
def __init__(self, def __init__(self,
@ -58,6 +59,8 @@ class Console:
"help": self.__create_help_message, "help": self.__create_help_message,
} }
self.is_run = False
self.get_IO = ConsoleIO self.get_IO = ConsoleIO
def __debug(self, *x): def __debug(self, *x):
@ -99,8 +102,11 @@ class Console:
return message return message
def __create_message(self, text, r="\r"): def __create_message(self, text, r="\r"):
self.__debug("create message to output") self.__debug(f"create message to output, is_run: {self.is_run}")
return r + self.__prompt_out + " " + text + "\n\r" + self.__prompt_in + " " text += "\n"
if self.is_run:
text += "\r" + self.__prompt_in + " "
return r + self.__prompt_out + " " + text
@property @property
def alias(self) -> dict: def alias(self) -> dict:
@ -127,8 +133,7 @@ class Console:
return self.__alias.copy() return self.__alias.copy()
def write(self, s: AnyStr, r="\r"): def write(self, s: AnyStr, r="\r"):
s = s.replace("\n\t", "\n" + self.__prompt_out + " ").replace("\t", " ") self.__file.write(self.__create_message(s, r))
ConsoleIO.write(self.__create_message(s, r))
def log(self, s: AnyStr, r='\r') -> None: def log(self, s: AnyStr, r='\r') -> None:
self.write(s, r) self.write(s, r)
@ -143,12 +148,17 @@ class Console:
file: str or None = None, file: str or None = None,
flush: bool = False, flush: bool = False,
loading: bool = False) -> None: loading: bool = False) -> None:
self.__debug(f"Used __builtins_print; is_run: {self.is_run}")
val = list(values) val = list(values)
if len(val) > 0: if len(val) > 0:
val.insert(0, "\r" + self.__prompt_out) val.insert(0, "\r" + self.__prompt_out)
if not loading: if not loading:
val.append("\r\n" + self.__prompt_in + " ") if self.is_run:
end = "" if end is None else end val.append("\r\n" + self.__prompt_in + " ")
end = "" if end is None else end
else:
if end is None:
end = "\n"
self.__print(*tuple(val), sep=sep, end=end, file=file, flush=flush) self.__print(*tuple(val), sep=sep, end=end, file=file, flush=flush)
def logger_hook(self) -> None: def logger_hook(self) -> None:
@ -160,7 +170,7 @@ class Console:
msg = cls.format(record) msg = cls.format(record)
ConsoleIO.write(self.__create_message(msg)) ConsoleIO.write(self.__create_message(msg))
cls.flush() cls.flush()
except RecursionError: # See issue 36272 except RecursionError:
raise raise
except Exception: except Exception:
cls.handleError(record) cls.handleError(record)
@ -173,8 +183,10 @@ class Console:
:return: None :return: None
""" """
self.__debug("used builtins_hook") self.__debug("used builtins_hook")
builtins.Console = Console builtins.Console = Console
builtins.console = self builtins.console = self
builtins.print = self.__builtins_print builtins.print = self.__builtins_print
def run(self) -> None: def run(self) -> None:
@ -182,6 +194,7 @@ class Console:
def run(self) -> None: def run(self) -> None:
:return: None :return: None
""" """
self.is_run = True
self.run_while(True) self.run_while(True)
def run_while(self, whl) -> None: def run_while(self, whl) -> None:

View File

@ -31,7 +31,8 @@ class Console(object):
file: SupportsWrite[str] or None = Console, file: SupportsWrite[str] or None = Console,
debug: bool = False) -> None: debug: bool = False) -> None:
self.get_IO: ConsoleIO self.get_IO: ConsoleIO = ConsoleIO
self.is_run: bool = False
def __getitem__(self, item): ... def __getitem__(self, item): ...
@property @property

View File

@ -4,7 +4,11 @@ import os
from console import Console, ConsoleIO from console import Console, ConsoleIO
# Init modules # Init modules
cli = Console() # Console(debug=True) cli = Console(prompt_in=">",
prompt_out="]:",
not_found="Command \"%s\" not found in alias.",
file=ConsoleIO,
debug=False)
logging.basicConfig(level=logging.NOTSET, format="%(asctime)s - %(name)-5s - %(levelname)-7s - %(message)s") logging.basicConfig(level=logging.NOTSET, format="%(asctime)s - %(name)-5s - %(levelname)-7s - %(message)s")
@ -13,7 +17,7 @@ def cli_print():
cli.log("cli.og") cli.log("cli.og")
cli.write("cli.write") cli.write("cli.write")
print("\r...", end="\n\n\n") print(end="\n\n\n")
def logger_preview(): def logger_preview():
@ -27,7 +31,7 @@ def logger_preview():
logging.error("Error log") logging.error("Error log")
logging.info("Info log") logging.info("Info log")
print("\r...", end="\n\n\n") print(end="\n\n\n")
def builtins_preview(): def builtins_preview():
@ -36,7 +40,6 @@ def builtins_preview():
# Output below without hook # Output below without hook
print("No builtins_hook here") print("No builtins_hook here")
print("No builtins_hook here, but file=cli, end=''", file=cli, end="")
cli.builtins_hook() cli.builtins_hook()
@ -51,7 +54,7 @@ def builtins_preview():
console['[] log'] console['[] log']
console << "<< log" console << "<< log"
ConsoleIO.write("\r...\n\n") # Or console.get_IO.write("\r...\n\n") ConsoleIO.write("\n\n") # Or console.get_IO.write("\n\n")
def cli_echo(x: str): def cli_echo(x: str):
@ -62,21 +65,22 @@ def cli_echo(x: str):
return message return message
def cli_error(x): def cli_error(x: str):
""" Print error message """ """ Print error message """
raise Exception("Test error message") raise Exception("Test error message")
def cli_exit(): def cli_exit(x: str):
""" Kill process """ """ Kill process """
pid = os.getpid() pid = os.getpid()
os.system(f"kill {pid}") os.system(f"kill {pid}")
def cli_mode(): def cli_mode():
print("type help")
ConsoleIO.write("\rtype help\n")
cli.add("echo", cli_echo) cli.add("echo", cli_echo)
cli.add("error", cli_error) cli.add("error", cli_error)
@ -90,6 +94,6 @@ def cli_mode():
if __name__ == '__main__': if __name__ == '__main__':
cli_print() cli_print()
logger_preview() # logger_preview()
builtins_preview() # builtins_preview()
cli_mode() # cli_mode()