所以我一直在研究我的這個小專案,它涉及使用套接字從“零開始”構建簡單的 TCP 反向 shell。下面的代碼有沒有辦法減少冗余?
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())
uj5u.com熱心網友回復:
一種選擇是將命令映射到字典:
from typing import Dict, Callable
commands: Dict[str, Callable] = {
"camera": open_camera,
"fullscreen": full_screen,
"exit_prog": exit_prog
...
}
然后:
if commmand in commands:
commands[command]() # Get the function out of the dictionary, then call it
else:
s.send("Invalid command !\n".encode())
uj5u.com熱心網友回復:
因此,您可以使用 Python 的有用getattr方法。例子:getattr(some_object, command)()
因此,您最終可能會得到如下所示的內容:
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)()
uj5u.com熱心網友回復:
你可以試試這個
try:
{"camera": open_camera(), "fullscreen": full_screen()}.get(command, s.send("Invalid command !\n".encode()))
except:
pass
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/520778.html
上一篇:套接字程式獲得出生年份
