]> git.ipfire.org Git - nitsi.git/blame - src/nitsi/cmd.py
Add interactive error handling
[nitsi.git] / src / nitsi / cmd.py
CommitLineData
4ac093dc
JS
1
2
3class CMD():
4 def __init__(self, prompt="", help={}, intro = ""):
5 self.prompt = "nitsi: "
6 self.help_min = {"help": "Shows this help message", "?": "Same as 'help'"}
7 self.help = help
8
9 if prompt != "":
10 self.prompt = prompt
11
12 self.intro = ""
13
14 if intro != "":
15 self.intro = intro
16
17 def print_intro(self, intro=""):
18 if intro == "":
19 intro = self.intro
20 self.print_to_cmd(intro)
21
22 def print_to_cmd(self, string):
23 print(string, end="\n")
24
25 def read_from_cmd(self, prompt=""):
26 if prompt == "":
27 prompt = self.prompt
28 return input(prompt)
29
30 def get_input(self, valid_commands=[], help={}):
31 valid_commands = valid_commands + [ "?", "help" ]
32 input=""
33
34 while True:
35 input = self.read_from_cmd()
36 if input not in valid_commands:
37 self.print_to_cmd("{} is not valid command.".format(input))
38 continue
39
40 # print help
41 if input == "help" or input == "?":
42 self.print_help(help=help)
43 continue
44
45 # if we get here we get a valid input
46 break
47
48 return input
49
50 def print_help(self, help={}):
51 if len(help) == 0:
52 help = self.help
53
54 # Update help with help_min
55 tmp_help = self.help_min
56 tmp_help.update(help)
57 help = tmp_help
58
59 for key in help:
60 self.print_to_cmd("{}: {}".format(key, help[key]))