So I’ve been working on this little project of mine which involves building simple TCP reverse shell from "scratch" using sockets. Is there a way for the code below to be less redundant?
elif command == "camera":
try:
open_camera()
except:
pass
elif command == "fullscreen":
full_screen()
elif command == "exit_prog":
exit_prog()
elif command == "minimise":
minimise()
elif command == "enter":
enter()
elif command == "right":
right()
elif command =="left":
left()
elif command == "break":
break
else:
s.send("Invalid command !\n".encode())
>Solution :
One option is to map the commands to a dictionary:
from typing import Dict, Callable
commands: Dict[str, Callable] = {
"camera": open_camera,
"fullscreen": full_screen,
"exit_prog": exit_prog
...
}
Then:
if commmand in commands:
commands[command]() # Get the function out of the dictionary, then call it
else:
s.send("Invalid command !\n".encode())