This commit is contained in:
SantaSpeen 2022-02-22 22:22:23 +03:00
parent 494d375a4b
commit a95bb2abab
5 changed files with 79 additions and 25 deletions

View File

@ -1,6 +1,6 @@
# CLI in Python
#### Версия для русских: [здесь](./README_RU.md)
##### Версия для русских: [здесь](./README_RU.md)
## Command-line interface for programs on Python3
@ -8,6 +8,9 @@
```python
from console import Console
import platform
import getpass
cli = Console(prompt_in=">", prompt_out="]:")
def cli_echo(x: str):
@ -17,7 +20,17 @@ def cli_echo(x: str):
return message
cli.add("help", cli_echo) # Add commands
def cli_uname():
""" Print uname information. """
uname = platform.uname()
user = getpass.getuser()
return f"{user}@{uname.node} -> {uname.system} {uname.release} ({uname.version})"
# Add commands
cli.add("help", cli_echo, echo=True) # With echo
cli.add("uname", cli_uname) # Without echo
cli.run()
```
@ -90,6 +103,9 @@ console << "<< log"
# ]: << log
```
If you use IDE, you mast update `builtins.pyi` with `scr/builtins_fix.pyi`. <br/>
Copy all from `builtins_fix.pyi` and insert into `builtins.pyi` at line `131` below `class type(object)`.
## Links
* [Author's Telegram](https://t.me/SantaSpeen "SantaSpeen"): https://t.me/SantaSpeen

View File

@ -6,6 +6,9 @@
```python
from console import Console
import platform
import getpass
cli = Console(prompt_in=">", prompt_out="]:")
def cli_echo(x: str):
@ -15,7 +18,17 @@ def cli_echo(x: str):
return message
cli.add("help", cli_echo) # Add commands
def cli_uname():
""" Print uname information. """
uname = platform.uname()
user = getpass.getuser()
return f"{user}@{uname.node} -> {uname.system} {uname.release} ({uname.version})"
# Add commands
cli.add("help", cli_echo, echo=True) # With echo
cli.add("uname", cli_uname) # Without echo
cli.run()
```
@ -88,6 +101,9 @@ console << "<< log"
# ]: << log
```
Если вы используете IDE, можно обновить `builtins.pyi` используя `scr/builtins_fix.pyi`. <br/>
Скопируйте всё из `builtins_fix.pyi` и вставте в `builtins.pyi` на `131` линию, до `class type(object)`.
## Ссылки
* [Мой Telegram](https://t.me/SantaSpeen "SantaSpeen"): https://t.me/SantaSpeen

View File

@ -2,7 +2,7 @@
# Developed by Ahegao Devs
# Written by: SantaSpeen
# Version 1.0
# Version 1.1
# Licence: MIT
# (c) ahegao.ovh 2022
@ -55,9 +55,9 @@ class Console:
self.__file = file
self.__alias = {
"help": self.__create_help_message,
}
self.__alias = dict()
self.add("help", self.__create_help_message, True)
self.is_run = False
@ -94,7 +94,7 @@ class Console:
message = f"%{max_len}s : Help message\n" % "Command"
for k, v in self.__alias.items():
doc = v.__doc__
doc = v['f'].__doc__
if doc is None:
doc = " No help message found"
message += f" %{max_len}s :%s\n" % (k, doc)
@ -111,25 +111,27 @@ class Console:
@property
def alias(self) -> dict:
"""
@property
def alias(self) -> dict:
:return: dict of alias
:return: Copy of commands alias
"""
return self.__alias.copy()
def add(self, key: str, func) -> dict:
def add(self, key: str, func, echo=False) -> dict:
"""
def add(self, key: str, func) -> dict:
:param key:
:param func:
:return:
add(key: str, func, echo=False) -> dict
:param key: Command name. This name added to alias of commands
:param func: Function or lambda function to run, when called key
:param echo: If you need echo from command set as True
:return: Copy of commands alias
"""
key = key.format(" ", "-")
if not isinstance(key, str):
raise TypeError("key must be string")
self.__debug(f"added user command: key={key}; func={func}")
self.__alias.update({key: func})
self.__debug(f"added user command: key={key}; func={func}; echo={echo}")
self.__alias.update({key: {"f": func, "e": echo}})
return self.__alias.copy()
def write(self, s: AnyStr, r="\r"):
@ -162,6 +164,10 @@ class Console:
self.__print(*tuple(val), sep=sep, end=end, file=file, flush=flush)
def logger_hook(self) -> None:
"""
def logger_hook(self) -> None:
:return: None
"""
self.__debug("used logger_hook")
@ -212,10 +218,14 @@ class Console:
if cmd == "":
pass
else:
command = self.__alias.get(cmd)
if command:
x = cmd_in[len(cmd) + 1:]
output = command(x)
command_object = self.__alias.get(cmd)
if command_object:
command = command_object['f']
if command_object['e']:
x = cmd_in[len(cmd) + 1:]
output = command(x)
else:
output = command()
if isinstance(output, str):
self.log(output)
else:

View File

@ -37,7 +37,7 @@ class Console(object):
def __getitem__(self, item): ...
@property
def alias(self) -> dict: ...
def add(self, key: str, func: function) -> dict: ...
def add(self, key: str, func: function, echo: bool=False) -> dict: ...
def log(self, s: AnyStr, r='\r') -> None: ...
def write(self, s: AnyStr, r='\r') -> None: ...
def logger_hook(self) -> None: ...

View File

@ -1,5 +1,7 @@
import getpass
import logging
import os
import platform
from console import Console, ConsoleIO
@ -65,26 +67,36 @@ def cli_echo(x: str):
return message
def cli_error(x: str):
def cli_error():
""" Print error message """
raise Exception("Test error message")
def cli_exit(x: str):
def cli_exit():
""" Kill process """
pid = os.getpid()
print(f"\r$ kill {pid}")
os.system(f"kill {pid}")
def cli_mode():
def cli_uname():
""" Print uname information """
uname = platform.uname()
user = getpass.getuser()
return f"{user}@{uname.node} -> {uname.system} {uname.release} ({uname.version})"
def cli_mode():
ConsoleIO.write("\rtype help\n")
cli.add("echo", cli_echo)
cli.add("echo", cli_echo, echo=True)
cli.add("error", cli_error)
cli.add("exit", cli_exit)
cli.add("uname", cli_uname)
cli.run()