Home > OS >  Is there a way to be less redundant?
Is there a way to be less redundant?

Time:10-23

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

CodePudding user response:

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

CodePudding user response:

So you can use Python's helpful getattr method. Example: getattr(some_object, command)()

So you may end up with something that looks like:

class SomeClass:
    def __init__(self):
        # possibly start loop here?
    def open_camera(self):
        pass # ...
    def fullscreen(self):
        pass # ...
    def exit_prog(self):
        pass # ...
    # Keep going for each command you need...
    def break(self):
        # exit out of loop...

# then create object & use it to handle commmands
so = SomeClass()
getattr(so, command)()

CodePudding user response:

You can try this

try:
    {"camera": open_camera(), "fullscreen": full_screen()}.get(command, s.send("Invalid command !\n".encode()))
except:
    pass
  • Related