【问题标题】:How to autocomplete only one argument in Cmd2 with argparse如何使用 argparse 在 Cmd2 中仅自动完成一个参数
【发布时间】:2019-12-19 02:45:05
【问题描述】:

如何使用 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 中进行选择)。我想根据“类型”参数自动完成“值”参数。如果值是“数字”,我用数字列表完成它。如果 value 是 'alphabet',我用字母列表完成它。

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

谢谢,

【问题讨论】:

    标签: python autocomplete argparse cmd2


    【解决方案1】:

    我在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()
    
    

    【讨论】:

      猜你喜欢
      • 2018-07-25
      • 2012-05-05
      • 2017-08-23
      • 1970-01-01
      • 2018-06-08
      • 1970-01-01
      • 2010-09-10
      • 1970-01-01
      • 2015-02-26
      相关资源
      最近更新 更多