如何使用python的cmd获取第一个字母命令?

时间:2015-07-24 07:29:58

标签: python

我想键入" c"在我的命令行中,按Enter键并让它运行"命令"命令。此代码执行我想要的操作,但它不使用cmd。我想用cmd:

import sys

def command():
    print("This is a command")

def quit():
    print("goodbye")
    sys.exit()

def take(item=None):
    if item:
        print("You take %s" % item)
    else:
        print("What would you like to take?")

commands = {
'command': command,
'quit': quit,
'take': take,
}

def complete(text, state):
    print("Here is the text: %s and here is the state %s" % (text, state))

def my_loop():
    while True:
        c = raw_input("\n>")
        if c.strip():
            c = c.split(' ', 1)
            for command in commands:
                if command.startswith(c[0]):c[0] = command
            func = commands.get(c[0], None)
            if func:
                if len(c) == 1:func()
                else:func(c[1])
            else:print("I don't understand that command")

my_loop()

使用cmd时也是如此,但它没有运行"命令"键入" c"并点击进入。

import sys, cmd

class Mcmd(cmd.Cmd):
    prompt = '\n>'

    def default(self, arg):
        print("I do not understand that command. Type 'help' for a list of commands")

    def do_command(self, line):
        print("This is a command")

    def do_quit(self, arg):
        print("See you")
        return True

Mcmd().cmdloop()

如何启动命令以触发"命令"或者"退出"命令使用cmd? (" c"," co"," com"," comm" ...) 全部触发"命令"功能。 我正在考虑使用新的textwrap模块,但textwrap存在跨平台问题。 有没有其他方法可以做到这一点? 谢谢,

1 个答案:

答案 0 :(得分:0)

您已经设法弄清楚如何覆盖默认方法,因此您可以扩展它以在Mcmd类中查找兼容的方法。尝试这样的事情:

    def default(self, line):
        command, arg, line = self.parseline(line)
        func = [getattr(self, n) for n in self.get_names()
            if n.startswith('do_' + command)]
        if len(func) == 1:
            return func[0](arg)
        print("I do not understand that command. Type 'help' for a list of commands")

运行

>a
I do not understand that command. Type 'help' for a list of commands

>c
This is a command

>ca
I do not understand that command. Type 'help' for a list of commands

>co
This is a command

>q
See you

虽然技术上是Aliases for commands with Python cmd module的副本,但答案并不完全;它没有正确解决模棱两可的案例(比如你同时得到do_commanddo_copycco的输入会发生什么?这里只有在有单一匹配时才会返回。

或者Python cmd module command aliases是一个可能的答案,但这只是单调乏味。