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

View File

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

View File

@ -4,7 +4,11 @@ import os
from console import Console, ConsoleIO
# 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")
@ -13,7 +17,7 @@ def cli_print():
cli.log("cli.og")
cli.write("cli.write")
print("\r...", end="\n\n\n")
print(end="\n\n\n")
def logger_preview():
@ -27,7 +31,7 @@ def logger_preview():
logging.error("Error log")
logging.info("Info log")
print("\r...", end="\n\n\n")
print(end="\n\n\n")
def builtins_preview():
@ -36,7 +40,6 @@ def builtins_preview():
# Output below without hook
print("No builtins_hook here")
print("No builtins_hook here, but file=cli, end=''", file=cli, end="")
cli.builtins_hook()
@ -51,7 +54,7 @@ def builtins_preview():
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):
@ -62,21 +65,22 @@ def cli_echo(x: str):
return message
def cli_error(x):
def cli_error(x: str):
""" Print error message """
raise Exception("Test error message")
def cli_exit():
def cli_exit(x: str):
""" Kill process """
pid = os.getpid()
os.system(f"kill {pid}")
def cli_mode():
print("type help")
ConsoleIO.write("\rtype help\n")
cli.add("echo", cli_echo)
cli.add("error", cli_error)
@ -90,6 +94,6 @@ def cli_mode():
if __name__ == '__main__':
cli_print()
logger_preview()
builtins_preview()
cli_mode()
# logger_preview()
# builtins_preview()
# cli_mode()