42 lines
1.1 KiB
Python
42 lines
1.1 KiB
Python
class Console:
|
|
|
|
def __init__(self, prompt: str, unknown_text="Unknown Command. Try help to see all commands."):
|
|
self.prompt = prompt
|
|
self.unknown_text = unknown_text
|
|
self.run = True
|
|
self.help = {}
|
|
self.commands = {}
|
|
|
|
self.reg_command("help", "This help message", self._print_help)
|
|
|
|
def reg_command(self, name, help_message, callback):
|
|
self.help[name] = help_message
|
|
self.commands[name] = callback
|
|
|
|
def stop(self):
|
|
self.run = False
|
|
|
|
def _print_help(self):
|
|
max_len = 0
|
|
for i in self.help.keys():
|
|
if len(i) > max_len:
|
|
max_len = len(i)
|
|
|
|
print("Available commands:")
|
|
for name, text in self.help.items():
|
|
print(f"{name:<{max_len}} -- {text}")
|
|
|
|
def _start(self):
|
|
while self.run:
|
|
cmd = input(self.prompt).strip()
|
|
if cmd not in self.commands:
|
|
print(self.unknown_text)
|
|
continue
|
|
self.commands[cmd]()
|
|
|
|
def start(self):
|
|
try:
|
|
self._start()
|
|
except KeyboardInterrupt:
|
|
pass
|