首页 > 解决方案 > 如何使用 argparse 在 Cmd2 中仅自动完成一个参数

问题描述

如何使用 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()

使用此代码,我可以自动完成“类型”参数(在 add_argument 中进行选择)。我想根据“类型”参数自动完成“值”参数。如果值是“数字”,我用数字列表完成它。如果值是“字母”,我用字母列表完成它。

有什么方法可以正确实现这种行为?还是我应该实现自己的 complete_list 方法?

谢谢,

标签: pythonautocompleteargparsecmd2

解决方案


我找到了completer_method使用Cmd2ArgumentParser. 它尚未记录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()


推荐阅读