mirror of
https://github.com/SantaSpeen/CLI-in-Python.git
synced 2025-07-01 15:25:31 +00:00
1.1
This commit is contained in:
parent
494d375a4b
commit
a95bb2abab
20
README.md
20
README.md
@ -1,6 +1,6 @@
|
|||||||
# CLI in Python
|
# CLI in Python
|
||||||
|
|
||||||
#### Версия для русских: [здесь](./README_RU.md)
|
##### Версия для русских: [здесь](./README_RU.md)
|
||||||
|
|
||||||
## Command-line interface for programs on Python3
|
## Command-line interface for programs on Python3
|
||||||
|
|
||||||
@ -8,6 +8,9 @@
|
|||||||
|
|
||||||
```python
|
```python
|
||||||
from console import Console
|
from console import Console
|
||||||
|
import platform
|
||||||
|
import getpass
|
||||||
|
|
||||||
cli = Console(prompt_in=">", prompt_out="]:")
|
cli = Console(prompt_in=">", prompt_out="]:")
|
||||||
|
|
||||||
def cli_echo(x: str):
|
def cli_echo(x: str):
|
||||||
@ -17,7 +20,17 @@ def cli_echo(x: str):
|
|||||||
|
|
||||||
return message
|
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()
|
cli.run()
|
||||||
```
|
```
|
||||||
@ -90,6 +103,9 @@ console << "<< log"
|
|||||||
# ]: << 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
|
## Links
|
||||||
|
|
||||||
* [Author's Telegram](https://t.me/SantaSpeen "SantaSpeen"): https://t.me/SantaSpeen
|
* [Author's Telegram](https://t.me/SantaSpeen "SantaSpeen"): https://t.me/SantaSpeen
|
||||||
|
18
README_RU.md
18
README_RU.md
@ -6,6 +6,9 @@
|
|||||||
|
|
||||||
```python
|
```python
|
||||||
from console import Console
|
from console import Console
|
||||||
|
import platform
|
||||||
|
import getpass
|
||||||
|
|
||||||
cli = Console(prompt_in=">", prompt_out="]:")
|
cli = Console(prompt_in=">", prompt_out="]:")
|
||||||
|
|
||||||
def cli_echo(x: str):
|
def cli_echo(x: str):
|
||||||
@ -15,7 +18,17 @@ def cli_echo(x: str):
|
|||||||
|
|
||||||
return message
|
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()
|
cli.run()
|
||||||
```
|
```
|
||||||
@ -88,6 +101,9 @@ console << "<< log"
|
|||||||
# ]: << 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
|
* [Мой Telegram](https://t.me/SantaSpeen "SantaSpeen"): https://t.me/SantaSpeen
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
# Developed by Ahegao Devs
|
# Developed by Ahegao Devs
|
||||||
# Written by: SantaSpeen
|
# Written by: SantaSpeen
|
||||||
# Version 1.0
|
# Version 1.1
|
||||||
# Licence: MIT
|
# Licence: MIT
|
||||||
# (c) ahegao.ovh 2022
|
# (c) ahegao.ovh 2022
|
||||||
|
|
||||||
@ -55,9 +55,9 @@ class Console:
|
|||||||
|
|
||||||
self.__file = file
|
self.__file = file
|
||||||
|
|
||||||
self.__alias = {
|
self.__alias = dict()
|
||||||
"help": self.__create_help_message,
|
|
||||||
}
|
self.add("help", self.__create_help_message, True)
|
||||||
|
|
||||||
self.is_run = False
|
self.is_run = False
|
||||||
|
|
||||||
@ -94,7 +94,7 @@ class Console:
|
|||||||
|
|
||||||
message = f"%{max_len}s : Help message\n" % "Command"
|
message = f"%{max_len}s : Help message\n" % "Command"
|
||||||
for k, v in self.__alias.items():
|
for k, v in self.__alias.items():
|
||||||
doc = v.__doc__
|
doc = v['f'].__doc__
|
||||||
if doc is None:
|
if doc is None:
|
||||||
doc = " No help message found"
|
doc = " No help message found"
|
||||||
message += f" %{max_len}s :%s\n" % (k, doc)
|
message += f" %{max_len}s :%s\n" % (k, doc)
|
||||||
@ -111,25 +111,27 @@ class Console:
|
|||||||
@property
|
@property
|
||||||
def alias(self) -> dict:
|
def alias(self) -> dict:
|
||||||
"""
|
"""
|
||||||
|
@property
|
||||||
def alias(self) -> dict:
|
def alias(self) -> dict:
|
||||||
:return: dict of alias
|
:return: Copy of commands alias
|
||||||
"""
|
"""
|
||||||
return self.__alias.copy()
|
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:
|
add(key: str, func, echo=False) -> dict
|
||||||
:param key:
|
:param key: Command name. This name added to alias of commands
|
||||||
:param func:
|
:param func: Function or lambda function to run, when called key
|
||||||
:return:
|
:param echo: If you need echo from command set as True
|
||||||
|
:return: Copy of commands alias
|
||||||
"""
|
"""
|
||||||
|
|
||||||
key = key.format(" ", "-")
|
key = key.format(" ", "-")
|
||||||
|
|
||||||
if not isinstance(key, str):
|
if not isinstance(key, str):
|
||||||
raise TypeError("key must be string")
|
raise TypeError("key must be string")
|
||||||
self.__debug(f"added user command: key={key}; func={func}")
|
self.__debug(f"added user command: key={key}; func={func}; echo={echo}")
|
||||||
self.__alias.update({key: func})
|
self.__alias.update({key: {"f": func, "e": echo}})
|
||||||
return self.__alias.copy()
|
return self.__alias.copy()
|
||||||
|
|
||||||
def write(self, s: AnyStr, r="\r"):
|
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)
|
self.__print(*tuple(val), sep=sep, end=end, file=file, flush=flush)
|
||||||
|
|
||||||
def logger_hook(self) -> None:
|
def logger_hook(self) -> None:
|
||||||
|
"""
|
||||||
|
def logger_hook(self) -> None:
|
||||||
|
:return: None
|
||||||
|
"""
|
||||||
|
|
||||||
self.__debug("used logger_hook")
|
self.__debug("used logger_hook")
|
||||||
|
|
||||||
@ -212,10 +218,14 @@ class Console:
|
|||||||
if cmd == "":
|
if cmd == "":
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
command = self.__alias.get(cmd)
|
command_object = self.__alias.get(cmd)
|
||||||
if command:
|
if command_object:
|
||||||
x = cmd_in[len(cmd) + 1:]
|
command = command_object['f']
|
||||||
output = command(x)
|
if command_object['e']:
|
||||||
|
x = cmd_in[len(cmd) + 1:]
|
||||||
|
output = command(x)
|
||||||
|
else:
|
||||||
|
output = command()
|
||||||
if isinstance(output, str):
|
if isinstance(output, str):
|
||||||
self.log(output)
|
self.log(output)
|
||||||
else:
|
else:
|
||||||
|
@ -37,7 +37,7 @@ class Console(object):
|
|||||||
def __getitem__(self, item): ...
|
def __getitem__(self, item): ...
|
||||||
@property
|
@property
|
||||||
def alias(self) -> dict: ...
|
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 log(self, s: AnyStr, r='\r') -> None: ...
|
||||||
def write(self, s: AnyStr, r='\r') -> None: ...
|
def write(self, s: AnyStr, r='\r') -> None: ...
|
||||||
def logger_hook(self) -> None: ...
|
def logger_hook(self) -> None: ...
|
||||||
|
20
src/main.py
20
src/main.py
@ -1,5 +1,7 @@
|
|||||||
|
import getpass
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
import platform
|
||||||
|
|
||||||
from console import Console, ConsoleIO
|
from console import Console, ConsoleIO
|
||||||
|
|
||||||
@ -65,26 +67,36 @@ def cli_echo(x: str):
|
|||||||
return message
|
return message
|
||||||
|
|
||||||
|
|
||||||
def cli_error(x: str):
|
def cli_error():
|
||||||
""" Print error message """
|
""" Print error message """
|
||||||
|
|
||||||
raise Exception("Test error message")
|
raise Exception("Test error message")
|
||||||
|
|
||||||
|
|
||||||
def cli_exit(x: str):
|
def cli_exit():
|
||||||
""" Kill process """
|
""" Kill process """
|
||||||
|
|
||||||
pid = os.getpid()
|
pid = os.getpid()
|
||||||
|
print(f"\r$ kill {pid}")
|
||||||
os.system(f"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")
|
ConsoleIO.write("\rtype help\n")
|
||||||
|
|
||||||
cli.add("echo", cli_echo)
|
cli.add("echo", cli_echo, echo=True)
|
||||||
cli.add("error", cli_error)
|
cli.add("error", cli_error)
|
||||||
cli.add("exit", cli_exit)
|
cli.add("exit", cli_exit)
|
||||||
|
cli.add("uname", cli_uname)
|
||||||
|
|
||||||
cli.run()
|
cli.run()
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user