你如何制作一个接受命令的控制台应用程序?

How do you make a console application which accepts commands?

我对 Python 和一般编程还比较陌生。我正在编写控制台应用程序。

如何编写在终端中接受命令的控制台应用程序?例如,终端本身如何接受命令并执行相应的任务。 "commands" 实际上只是应用程序中用户调用的函数吗?控制台界面本身只是一个功能吗?例如。 :

def console_interface():
    user_input = input()
    if user_input == "some_function":
        some_function()

    if user_input == "some_other_function":
        some_other_function()

虽然效率不高,但我知道上面的方法是有效的,因为我已经测试过了。这个总体思路是否正确?

Python 的标准库提供了一个完全封装 "console application that accepts commands" 功能的模块:参见 https://docs.python.org/3/library/cmd.html .

在该模块中,命令实际上是 class 的 方法 ,其中子class 是 cmd.Cmddo_this, do_that, 等等,按照命名约定。 https://docs.python.org/3/library/cmd.html#cmd-example的例子是丰富的"console accepting commands"海龟图形,你可以玩玩。

从教学上讲,您可能希望从 http://pymotw.com/2/cmd/ 中给出的更简单的示例开始——即 Python2,但功能几乎相同。 Python3中的优秀系列例子需要稍微适应运行,但应该不会太难。

例如,考虑第一个:

import cmd

class HelloWorld(cmd.Cmd):
    """Simple command processor example."""

    def do_greet(self, line):
        print "hello"

    def do_EOF(self, line):
        return True

if __name__ == '__main__':
    HelloWorld().cmdloop()

do_EOF 是用户终止标准输入(Unix 上的 control-D)时发生的情况;正如 https://docs.python.org/3/library/cmd.html#cmd.Cmd.cmdloop 所说,

An end-of-file on input is passed back as the string 'EOF'.

(在这种情况下,return True 终止程序)。

在 Python 2 而不是 3 中,您唯一需要更改为 运行 的是一行:

        print "hello"

必须变成

        print("hello")

因为 print 是 Python 2 中的语句,现在是 Python 3 中的函数。

我发现 http://www.opensource.apple.com/source/python/python-3/python/Lib/cmd.py 上的 cmd.py 来源也很有启发性,我建议将它们作为对 "dispatching" 世界的介绍进行研究...!