最近我開始了一個專案。我的目標是擁有一個腳本,一旦啟動,如果通過電子郵件發送指令,它就能夠控制主機上的操作。(我想要這個,所以我可以在我不在家時開始需要很長時間才能完成的任務)
我開始編程,不久之后我就可以發送電子郵件、接收電子郵件并分析其內容并采取行動回應電子郵件中的內容。
我通過使用輸入字典來做到這一點,它看起來像這樣:
contents_of_the_email = "!screen\n!wait 5\n!hotkey alt tab"
def wait(sec):
print(f"I did nothing for {sec} seconds!")
def no_operation():
print("Nothing")
def screenshot():
print("I took an image of the screen and send it to your email adress!")
def hotkey(*args):
print(f"I pressed the keys {', '.join(args)} at the same time")
FUNCTIONS = {
'':no_operation,
'!screen': screenshot,
'!hotkey': hotkey,
'!wait': wait
}
def call_command(command):
function, *args = command.split(' ')
FUNCTIONS[function](*args)
for line in contents_of_the_email.split("\n"):
call_command(line)
我總共有大約 25 個函式,每個函式都有自己的回應。我用簡單的列印陳述句替換了命令的實際代碼,因為不需要它們來理解或復制我的問題。
然后我想為命令添加別名,例如你可以輸入“!ss”而不是“!screen”。我確實使用字典中的另一行來實作這一點:
FUNCTIONS = {
'':no_operation,
'!screen': screenshot,
'!ss':screenshot,
'!hotkey': hotkey,
'!wait': wait
}
但我不喜歡這個。如果我為我計劃添加的每個別名都這樣做,它會填滿整個字典,這會使我的代碼非常混亂。有什么方法可以分別為命令定義別名,并且仍然保持字典簡潔明了?我希望在一個單獨的aliases.txt檔案中有這樣的東西:
screen: "!screen", "!ss","!screenshot","!image"
wait: "!wait","!pause","!sleep","!w"
hotkey: "!hk","!tk"
如果這在 python 中是可能的,我真的很感激知道!
uj5u.com熱心網友回復:
您可以使用 for 回圈相當輕松地從可呼叫物件的字典和快捷方式串列轉到可呼叫物件的快捷方式字典。
# long dict of shortcuts to callables
goal = {'A': 0, 'B': 0, 'C': 1}
# condensed dict, not in .txt, but storable in python
condensed = {0: ['A', 'B'], 1: ['C']}
# expand the condensed dict
commands = {}
for func, shortcuts in condensed.items():
for shortcut in shortcuts:
commands[shortcut] = func
# or with a comprehension
commands = {s: f for f, ls in condensed.items() for s in ls}
# verify expanded and goal are the same
assert commands == goal
uj5u.com熱心網友回復:
您可以使用以下解決方案:
import json
contents_of_the_email = "!screen\n!wait 5\n!hotkey alt tab"
def wait(sec):
print(f"I did nothing for {sec} seconds!")
def no_operation():
print("Nothing")
def screenshot():
print("I took an image of the screen and send it to your email address!")
def hotkey(*args):
print(f"I pressed the keys {', '.join(args)} at the same time")
# FUNCTIONS DICT FROM JSON
with open("aliases.json") as json_file:
aliases_json = json.load(json_file)
FUNCTIONS = {}
for func_name, aliases in aliases_json.items():
FUNCTIONS.update({alias: globals()[func_name] for alias in aliases})
def call_command(command):
function, *args = command.split(' ')
FUNCTIONS[function](*args)
for line in contents_of_the_email.split("\n"):
call_command(line)
別名.json:
{
"screenshot": ["!screen", "!ss","!screenshot","!image"],
"wait": ["!wait","!pause","!sleep","!w"],
"hotkey": ["!hk","!tk", "!hotkey"]
}
那是你要找的嗎?
uj5u.com熱心網友回復:
您可以通過首先創建一個將每個別名映射到其中一個函式的字典來做您想做的事情。這需要決議aliases.txt檔案——幸運的是這并不難。它利用ast.literal_eval()函式將檔案中參考的文字字串轉換為 Python 字串,以及使用內置globals()函式來查找給定檔案名的關聯函式。KeyError如果有任何對未定義函式的參考,將引發A。
請注意,我將您的aliases.txt檔案更改為以下內容(這更有意義):
screenshot: "!screen", "!ss","!screen","!image"
wait: "!wait","!pause","!sleep","!w"
hotkey: "!hk","!tk"
以下是如何執行此操作的可運行示例:
from ast import literal_eval
# The functions.
def wait(sec):
print(f"I did nothing for {sec} seconds!")
def no_operation():
print("Nothing")
def screenshot():
print("I took an image of the screen and send it to your email adress!")
def hotkey(*args):
print(f"I pressed the keys {', '.join(args)} at the same time")
# Create dictionary of aliases from text file.
aliases = {}
with open('aliases.txt') as file:
namespace = globals()
for line in file:
cmd, abbrs = line.rstrip().split(':')
abbrs = tuple(map(literal_eval, abbrs.replace(',', ' ').split()))
for abbr in abbrs:
aliases[abbr] = namespace[cmd]
def call_command(command):
function, *args = command.split(' ')
if function in aliases:
aliases[function](*args)
# Sample message.
contents_of_the_email = """\
!screen
!wait 5
!hk alt tab
"""
# Execute commands in email.
for line in contents_of_the_email.split("\n"):
call_command(line)
輸出:
I took an image of the screen and send it to your email adress!
I did nothing for 5 seconds!
I pressed the keys alt, tab at the same time
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/473183.html
上一篇:解耦包含串列作為特定鍵值的字典
