如何用cmd2自动补全参数解析器中的一个参数。
from cmd2 import Cmd, Cmd2ArgumentParser
import cmd2
numbers = ['0', '1', '2', '3', '4']
alphabet = ['a', 'b', 'c', 'd']
class Complete(Cmd):
parser = Cmd2ArgumentParser()
parser.add_argument("type", choices=['numbers', 'alphabet'])
parser.add_argument("value")
@cmd2.with_argparser(parser)
def do_list(self, args):
self.poutput(args.value)
if __name__ == "__main__":
app = Complete()
app.cmdloop()使用这段代码,我可以自动完成'type‘参数(在add_argument中有选择)。我想根据'type‘参数自动完成'value’参数。如果value是' numbers ',我会用数字列表来补全它。如果value是' alphabet ',我会用字母列表来补全它。
有没有办法正确地实现这种行为?或者我应该实现我自己的complete_list方法?
谢谢,
发布于 2019-08-13 17:24:45
我在Cmd2ArgumentParser中找到了一个使用关键字completer_method的解决方案。它还没有文档化的https://github.com/python-cmd2/cmd2/issues/748。
完整的解决方案
from cmd2 import Cmd, Cmd2ArgumentParser
import cmd2
numbers = ['0', '1', '2', '3', '4']
alphabet = ['a', 'b', 'c', 'd']
class Complete(Cmd):
def _complete_list_value(self, text, line, begidx, endidx):
type_ = line.split()[1]
if type_ == 'numbers':
x = [e for e in numbers if e.startswith(text)]
return [e for e in numbers if e.startswith(text)]
elif type_ == 'alphabet':
return [e for e in alphabet if e.startswith(text)]
else:
return []
parser = Cmd2ArgumentParser()
parser.add_argument("type", choices=['numbers', 'alphabet'])
parser.add_argument("value", completer_method=_complete_list_value)
@cmd2.with_argparser(parser)
def do_list(self, args):
self.poutput(args.value)
if __name__ == "__main__":
app = Complete()
app.cmdloop()https://stackoverflow.com/questions/57462568
复制相似问题