home_emulation/user_interface.py

54 строки
1.4 KiB
Python

import readline
import sys
import time
class user_interface(dict):
def __init__(self):
super().__init__(self)
self.add_command('quit', None)
def run(self):
readline.parse_and_bind("tab: complete")
readline.set_completer(self.completer)
print("\nEnter command: ")
while (True):
userfeedback = input('')
command = userfeedback.split(' ')[0]
if userfeedback == 'quit':
break
else:
self.call_it(userfeedback)
def call_it(self, userfeedback):
args = userfeedback.split(" ")
cmd = args.pop(0)
cb = self.get(cmd)
if callable(cb):
cb(*args)
else:
print("Unknown command \"%s\"" % name)
def add_command(self, name, callback):
self[name] = callback
def reduced_list(self, text):
"""
Create reduced completation list
"""
reduced_list = {}
for cmd in self.keys():
next_dot = cmd[len(text):].find('.')
if next_dot >= 0:
reduced_list[cmd[:len(text) + next_dot + 1]] = None
else:
reduced_list[cmd] = None
return reduced_list.keys()
def completer(self, text, state):
"""
Our custom completer function
"""
options = [x for x in self.reduced_list(text) if x.startswith(text)]
return options[state]