I try to use Cmd , but instead of adding all functions/commands separately, I want it to read functionnames from a dictionary and add them dynamically.
The preloop should add functions do_aa, complete_aa, do_bb and complete_bb.
The commands are taken from a dictionary, and added using setattr
import cmd
class C(cmd.Cmd):
commands = {'aa': ['aa1', 'aa2'],
'bb': ['bb1', 'bb2']}
def preloop(self):
for k, v in self.commands.items():
self.k = k
setattr(C, 'do_' + k, k)
setattr(C, 'complete_' + k, self.complete_)
def complete_(self, text, line, start_index, end_index):
if text:
return [
command for command in self.commands[self.k]
if command.startswith(text)
]
else:
return self.commands[self.k]
if __name__ == '__main__':
C().cmdloop()
The problem is that the autocomplete does not actually get the correct second-level commands:
(Cmd) aa
bb1 bb2 # should be aa1 aa2
(Cmd) bb
bb1 bb2
Why is this happening, and how can this be solved?