Skip to content

Commit

Permalink
1.0
Browse files Browse the repository at this point in the history
  • Loading branch information
SantaSpeen committed Feb 20, 2022
1 parent 931be6a commit 363a23d
Show file tree
Hide file tree
Showing 5 changed files with 79 additions and 27 deletions.
22 changes: 16 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,26 @@
# CLI in Python

#### Версия для русских: [здесь](./README_RU.md)

## Консольная оболочка для программ на питоне

### О проекте
### About

1.

### Usage

```python
from console import Console

1. Он не выложен
cli = Console(prompt_in=">", prompt_out="]:")

```

## Ссылки
## Links

* [Мой Telegram](https://t.me/SantaSpeen "SantaSpeen"): https://t.me/SantaSpeen
* [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 changes: 24 additions & 0 deletions README_RU.md
Original file line number Diff line number Diff line change
@@ -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)
29 changes: 21 additions & 8 deletions scr/console/Console.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

# Developed by Ahegao Devs
# Written by: SantaSpeen
# Version 1.0
# Licence: MIT
# (c) ahegao.ovh 2022

Expand Down Expand Up @@ -34,7 +35,7 @@ def __init__(self,
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,
Expand All @@ -58,6 +59,8 @@ def __init__(self,
"help": self.__create_help_message,
}

self.is_run = False

self.get_IO = ConsoleIO

def __debug(self, *x):
Expand Down Expand Up @@ -99,8 +102,11 @@ def __create_help_message(self, x) -> AnyStr:
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:
Expand All @@ -127,8 +133,7 @@ def add(self, key: str, func) -> dict:
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)
Expand All @@ -143,12 +148,17 @@ def __builtins_print(self,
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:
Expand All @@ -160,7 +170,7 @@ def emit(cls, record):
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)
Expand All @@ -173,15 +183,18 @@ def builtins_hook(self) -> None:
:return: None
"""
self.__debug("used builtins_hook")

builtins.Console = Console
builtins.console = self

builtins.print = self.__builtins_print

def run(self) -> None:
"""
def run(self) -> None:
:return: None
"""
self.is_run = True
self.run_while(True)

def run_while(self, whl) -> None:
Expand Down
3 changes: 2 additions & 1 deletion scr/console/Console.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
28 changes: 16 additions & 12 deletions scr/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@
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")


Expand All @@ -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():
Expand All @@ -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():
Expand All @@ -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()

Expand All @@ -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):
Expand All @@ -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)
Expand All @@ -90,6 +94,6 @@ def cli_mode():

if __name__ == '__main__':
cli_print()
logger_preview()
builtins_preview()
cli_mode()
# logger_preview()
# builtins_preview()
# cli_mode()

0 comments on commit 363a23d

Please sign in to comment.