简体   繁体   English

如何使用python的cmd获取首字母命令?

[英]How to get first letter commands using python's cmd?

I would like to type "c" in my commandline, hit enter and have it run the "command" command. 我想在命令行中输入“ c”,按回车键并运行“ command”命令。 This code does what I want, but it does not use cmd. 此代码可以实现我想要的功能,但不使用cmd。 I would like to use 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()

Here is the same using cmd, but it does not run the "command" command when I type "c" and hit enter. 这与使用cmd相同,但是当我键入“ c”并按Enter时,它不会运行“ command”命令。

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()

How can I get the start of the command to trigger the "command" or "quit" command using cmd? 如何使用cmd来启动命令的开头以触发“命令”或“退出”命令? ("c", "co", "com", "comm"...) all trigger the "command" function. (“ c”,“ co”,“ com”,“ comm” ...)都触发“命令”功能。 I was considering using the new textwrap module, but textwrap has problems being cross-platform. 我正在考虑使用新的textwrap模块,但textwrap在跨平台方面存在问题。 Is there any other way to do this? 还有其他方法吗? thank you, 谢谢,

You already managed to figure out how to override the default method, so you can extend that to look up a compatible method from within your Mcmd class. 您已经设法弄清楚如何覆盖默认方法,因此可以对其进行扩展以从Mcmd类中查找兼容的方法。 Try something like this: 尝试这样的事情:

    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")

Running that 运行那个

>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

While technically a duplicate of Aliases for commands with Python cmd module the answer isn't quite complete; 从技术上讲,它是使用Python cmd模块命令别名的重复,但答案还不是很完整。 it doesn't properly address ambiguous cases (say you got both do_command and do_copy , what should happen on the input of c and co ?). 它不能正确解决模棱两可的情况(例如,您同时拥有do_commanddo_copy ,那么在cco的输入上会发生什么?)。 Here it only returns if there is a singular match. 在此仅在存在单数匹配的情况下返回。

Alternatively Python cmd module command aliases is a possible answer, but it's just tedious. 另外,可能使用Python cmd模块命令别名作为答案,但这很乏味。

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

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