Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to be less redundant?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading