简体   繁体   English

Tab自动完成功能和python cmd模块中子命令的简单实现?

[英]Tab autocomplete and simple implementation of subcommands in python cmd module?

Is it possible to add tab autocomplete to subcommands in the python Cmd class in the cmd module? 是否可以在cmd模块的python Cmd类的子命令中添加选项卡自动完成功能? Say I am running my command loop, and I wanted to have a command called add , where I can then have a selection of animal names, like add horse , or add elephant . 假设我正在运行命令循环,我想有一个名为add的命令,然后可以在其中选择动物名称,例如add horseadd elephant How can I tab autocomplete for any sub commands, if at all possible? 如果有可能的话,如何为所有子命令设置自动完成选项卡?

One thing I'm doing for the actual project I'm working on is using different classes for different modes. 我正在为实际项目做的一件事是对不同的模式使用不同的类。 If you type whitelist , it runs another command loop in that class and is now in "whitelist" mode. 如果键入whitelist ,它将在该类中运行另一个命令循环,并且现在处于“白名单”模式。 You can then type exit to go back to the main command loop. 然后,您可以键入exit以返回到主命令循环。 That seems good for more heavyweight modes, but creating a whole new class the inherits Cmd seems a bit much for something as simple as adding different types of things like the example above. 对于更重量级的模式而言,这似乎不错,但是对于像添加上述示例之类的不同类型的事物这样简单的事情,创建一个继承Cmd全新类似乎有点过多。 So, what is the best way to add simple (in terms of code) sub commands for the Cmd class that can be tab completed? 那么,为可以用制表符完成的Cmd类添加简单(按代码表示)子命令的最佳方法是什么? Thanks. 谢谢。

The following works: 以下作品:

#!/usr/bin/env python


from __future__ import print_function


from cmd import Cmd
import readline  # noqa


class Zoo(Cmd):

    def __init__(self, animals):
        Cmd.__init__(self)

        self.animals = animals

    def do_add(self, animal):
        print("Animal {0:s} added".format(animal))

    def completedefault(self, text, line, begidx, endidx):
        tokens = line.split()
        if tokens[0].strip() == "add":
            return self.animal_matches(text)
        return []

    def animal_matches(self, text):
        matches = []
        n = len(text)
        for word in self.animals:
            if word[:n] == text:
                matches.append(word)
        return matches


animals = ["Bear", "Cat", "Cheetah", "Lion", "Zebra"]
zoo = Zoo(animals)
zoo.cmdloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM