Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a sort of command line for a python server

Tags:

python

command

I have been experimenting with Python socket servers and such. I came across an idea and I am having a hard time implementing it. I want the server side to be able to enter different commands, for starting and stopping the server, and performing various other tasks. My problem is, when I start having a lot of commands, my program ends up looking like spaghetti:

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

One of my friends who has been programming for a while said I should try and use a dictionary to store a function reference for each command. I created a dictionary like this:

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

And I would call these commands like this:

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

The problem with this method is that sometimes I want a command with multiple arguments and sometimes I don't. I want to be able to have different commands with varying arguments, specify their required arguments, and check to make sure the command is a valid command with all the required arguments. I am new to programming, and I have tried thinking of a clean way to implement this. I found nothing useful on google so hopefully someone can assist me. Thanks.

like image 854
coder guy Avatar asked Mar 10 '26 01:03

coder guy


1 Answers

If you know the commands' structure this is a task of parsing and it is up to the format. Other than that you can send variable length arguments using the star operator * (you can also send keyword arguments using ** but I'd start with this).

Here is a simple example:

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

Note than this will send all arguments as a string. This is a basic demonstration:

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

As mentioned in the comments to your question this is a very common task and libraries do exist to parse various common formats. One which is often used (I use it as well) is argparse.

like image 103
Reut Sharabani Avatar answered Mar 12 '26 14:03

Reut Sharabani