python - 如何使用 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 方法?
谢谢,
解决方案
我找到了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()
推荐阅读
- wpf - 为什么两个 Transform 不能与 Helix Toolkit 对象一起使用
- dart - 如何在每个特定页面上添加文本?
- pyomo - Pyomo:重新定义集合
- google-chrome - Chrome 扩展程序有关于 UTF-8 的 content.js 错误
- python - 如何搜索一个列表并查看所有这些项目是否在第二个列表中,然后打印(如果有)所有缺失的元素以及有多少?
- c# - 如何在 MVC 中使用 DB First Approach 从连接表中获取数据
- directx - 使用 DirectX 渲染两个元素时的时序不同步
- scala - Spark DataFrame 缓存不断增长
- java - 使用Java8排序并检查数字是否连续
- reactjs - ReactStrap NavLinks 在通过组件呈现时被破坏