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

我开始编程,不久之后我就可以发送邮箱、接收邮箱、分析它们的内容,并对邮箱中的内容做出响应.

contents_of_the_email ="!screen\n!wait 5\n!hotkey alt tab\n"
# 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 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 = "!screen\n!wait 5\n!hotkey alt tab\n"
# takes a screenshot waits 5 seconds and presses alt tab

for line in contents_of_the_email.split("\n"):
    call_command(line)

只需将函数和dict定义移动到单独的模块.

Python相关问答推荐

为什么符号没有按顺序添加?

什么相当于pytorch中的numpy累积ufunc

图像 pyramid .难以创建所需的合成图像

更改键盘按钮进入'

组/群集按字符串中的子字符串或子字符串中的字符串轮询数据框

如何从数据库上传数据到html?

用渐近模计算含符号的矩阵乘法

30个非DATETIME天内的累计金额

无法在Spyder上的Pandas中将本地CSV转换为数据帧

计算机找不到已安装的库'

Autocad使用pyautocad/comtypes将对象从一个图形复制到另一个图形

获取git修订版中每个文件的最后修改时间的最有效方法是什么?

python的文件. truncate()意外地没有截断'

如何从数据框列中提取特定部分并将该值填充到其他列中?

如何关联来自两个Pandas DataFrame列的列表项?

与同步和异步客户端兼容的Python函数

Match-Case构造中的对象可调用性测试

对列中的数字进行迭代,得到n次重复开始的第一个行号

正则表达式反向查找

Python键盘模块不会立即检测到按键