向用户输入添加命令



最近我开始了一个项目。我的目标是有一个脚本,一旦启动,如果指令通过电子邮件发送,就可以控制主机计算机上的操作。(我想要这个,这样我就可以在我离开家的时候开始做一些需要很长时间才能完成的任务)

我开始编程,不久之后,我可以发送电子邮件,接收电子邮件,分析其内容,并采取行动响应电子邮件中的内容。我是这样做的:我第一次尝试使用没有前缀的命令,但这会导致错误,所以我添加和"!"在每一个可以执行的命令的前面。然后,每当有新的一行时,我就会拆分电子邮件的内容。

contents_of_the_email ="!screenn!wait 5n!hotkey alt tabn"
# takes a screenshot waits 5 seconds and presses alt tab
lines = contents_of_the_email.count("n")
contents_of_the_email = contents_of_the_email.split("n")
for i in range(lines):
if "!screen" in contents_of_the_email[i]:
print("I took a screenshot and sent it to the specified email!")
elif "!wait " in contents_of_the_email[i]:
real = contents_of_the_email[i].split("!wait ")
print(f"I slept for {real[1]} seconds!")
elif "!hotkey " in contents_of_the_email[i]:
real = contents_of_the_email[i].split(" ")
print(f"I pressed the keys {real[1]} and {real[2]} at the same time!")

我用print语句替换了命令的实际代码,因为它们不需要理解我的问题或重新创建它。

现在这变得非常混乱。我添加了大约20个命令,它们开始相互冲突。我主要通过更改命令的名称来修复它,但它仍然是意大利面条代码。

我想知道是否有一种更优雅的方式向我的程序中添加命令,我希望有这样的工作方式:

def takeScreenshot():
print("I took a screenshot!")
addNewCommand(trigger="!screen",callback=takeScreenshot())

如果这在python中是可能的,我真的很想知道!D

您考虑过使用字典来调用函数吗?

def run_A():
print("A")
# code...
def run_B():
print("B")
# code...
def run_C():
print("C")
# code...
inputDict = {'a': run_A, 'b': run_B, 'c': run_C}
# After running the above 
>>> inputDict['a']()
A

尝试使用内置模块cmd:

import cmd, time
class ComputerControl(cmd.Cmd):
def do_screen(self, arg):
pass # Screenshot
def do_wait(self, length):
time.sleep(float(length))
def do_hotkey(self, arg):
...
inst = ComputerControl()
for line in contents_of_the_email.splitlines():
line = line.lstrip("!")  # Remove the '!'
inst.onecmd(line)

您可以尝试这样做:

def take_screenshot():
print("I took a screenshot!")

def wait(sec):
print(f"I waited for {sec} secs")

def hotkey(*args):
print(f"I pressed the keys {', '.join(args)} at the same time")

def no_operation():
print("Nothing")

FUNCTIONS = {
'!wait': wait,
'!screen': take_screenshot,
'!hotkey': hotkey,
'': no_operation
}

def call_command(command):
function, *args = command.split(' ')
FUNCTIONS[function](*args)

contents_of_the_email = "!screenn!wait 5n!hotkey alt tabn"
# takes a screenshot waits 5 seconds and presses alt tab
for line in contents_of_the_email.split("n"):
call_command(line)

只需将函数和字典定义移到单独的模块。

最新更新