为python创建一种命令行

2024-04-26 22:12:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在试验Python套接字服务器等。我遇到了一个想法,我很难实现它。我希望服务器端能够输入不同的命令,用于启动和停止服务器,以及执行各种其他任务。我的问题是,当我开始有很多命令时,我的程序最终看起来就像意大利面条:

if command == "start":
    print("Starting server")
    time.sleep(1)
    listener_thread.start()
elif command == "stop":
    print("Stopping server...")
    time.sleep(1)
    listener_thread.stop()
elif command in ["q", "quit"]:
    print("Quitting server...")
    time.sleep(1)
    for t in connections:
        t.stop()
    listener_thread.stop()
    exit()
else:
    print("Invalid command")

我的一个朋友已经编程一段时间了,他说我应该尝试使用字典来存储每个命令的函数引用。我编了一本这样的字典:

commands = {
    "start": cmd_start, # This would be a reference to cmd_start()
    "stop": cmd_stop, # Same here and so forth
    "quit": cmd_quit
}

我会这样称呼这些命令:

while True:
    command = input("enter a command: ")
    if command in commands:
        commands[command]()

此方法的问题是,有时我需要一个具有多个参数的命令,有时我不需要。我希望能够有具有不同参数的不同命令,指定它们所需的参数,并检查以确保该命令是具有所有所需参数的有效命令。我是编程新手,我尝试过用一种干净的方法来实现这一点。我在谷歌上找不到有用的东西,希望有人能帮我。谢谢。你知道吗


Tags: in命令cmd参数servertimesleepthread
2条回答

一个接近海报原始源代码的简单工作示例:

tokens = input("$ ").split()

command, arguments = tokens[0], tokens[1:]

def start_handler(start_line, end_line):
    print("Starting from {} to {}".format(start_line, end_line))

commands = {
  "start": start_handler    
}

commands[command](*arguments)

您可以输入如下命令:start 1 20,然后将1和20传递给启动处理程序。输出示例:

$  start 1 20
Starting from 1 to 20

如果您知道命令的结构,这是一个解析任务,它取决于格式。除此之外,您可以发送可变长度的参数using the star operator ^{}(您也可以使用**发送关键字参数,但我将从这个开始)。你知道吗

下面是一个简单的例子:

command = input("enter a command: ")
arguments = input("enter arguments separated by a single space: ").split()
if command in commands:
    commands[command](*arguments)

请注意,这样会将所有参数作为字符串发送。这是一个基本的演示:

>>> def func_with_three_params(a, b, c):
...     print a, b, c
... 
>>> three_args = "1 2 3".split()
>>> func_with_three_params(*three_args)
1 2 3

正如您问题的注释中所提到的,这是一项非常常见的任务,而且库确实存在,可以解析各种常见格式。一个经常使用的(我也使用它)是^{}。你知道吗

相关问题 更多 >