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? 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 . 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. You can then type exit to go back to the main command loop. 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. So, what is the best way to add simple (in terms of code) sub commands for the Cmd class that can be tab completed? Thanks.


以下工作:

#!/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()
链接地址: http://www.djcxy.com/p/56500.html

上一篇: 输入:拖放多个目录(多行)?

下一篇: 在python cmd模块中自动完成和简单实现子命令?