如何使用 argparse 在 Cmd2 中仅自动完成一个参数
How to autocomplete only one argument in Cmd2 with argparse
如何使用 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' 参数。如果值为 'numbers',我用数字列表完成它。如果值为 'alphabet',我用字母列表完成它。
有什么方法可以正确实现这种行为吗?还是我应该实现自己的 complete_list 方法?
谢谢,
我在 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()
如何使用 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' 参数。如果值为 'numbers',我用数字列表完成它。如果值为 'alphabet',我用字母列表完成它。
有什么方法可以正确实现这种行为吗?还是我应该实现自己的 complete_list 方法?
谢谢,
我在 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()