最近我開始了一個專案。我的目標是擁有一個腳本,一旦啟動,如果通過電子郵件發送指令,它就能夠控制主機上的操作。(我想要這個,所以我可以在我不在家時開始需要很長時間才能完成的任務)
我開始編程,不久之后我就可以發送電子郵件、接收電子郵件并分析其內容并采取行動回應電子郵件中的內容。我這樣做的方式是這樣的:我首先嘗試使用不帶前綴的命令,但這會導致錯誤,所以我添加了“!” 在每個可以采取的命??令之前。然后,只要有新行,我就會拆分電子郵件的內容。
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!")
我用列印陳述句替換了命令的實際代碼,因為不需要它們來理解我的問題或重新創建它。
現在這變得非常混亂。我添加了大約 20 個命令,它們開始發生沖突。我主要通過更改命令的名稱來修復它,但它仍然是意大利面條代碼。
我想知道是否有更優雅的方式向我的程式添加命令,我想要這樣的東西:
def takeScreenshot():
print("I took a screenshot!")
addNewCommand(trigger="!screen",callback=takeScreenshot())
如果這在 python 中是可能的,我真的很感激知道!謝謝 :D
uj5u.com熱心網友回復:
你可以嘗試這樣的事情:
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)
只需將函式和字典定義移動到單獨的模塊。
uj5u.com熱心網友回復:
您是否考慮過使用字典來呼叫您的函式?
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
uj5u.com熱心網友回復:
嘗試使用內置模塊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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/474995.html
