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.