最近我看到一篇關于有人制作一個可以控制啟動它的計算機的程式的帖子。(就是這個)向用戶輸入添加命令 我真的對它很感興趣,我想復制它并在此程序中提高我的 Python 技能。
在看了一些教程之后,我能夠發送和接收電子郵件并開始處理一些命令。首先,我添加了截屏功能,這是最重要的功能。然后我添加了函式和命令來做其他事情。然后我想添加一個幫助命令來顯示所有命令(如果沒有 args)和特定命令的描述(如果有 args)。我首先添加了一個不帶引數的,這是它的代碼:
import json
user_input = "$say hello\n$help"
def help(*args):
if args == ():
for func_name, aliases in info_json.items():
print(func_name)
else:
pass
#print the description for the command
def command1():
print("I am command 1.")
def command2():
print("I am command 2.")
def command3():
print("I am command 3.")
def say(*args):
print(f"You said i should say \"{' '.join(args)}\"! Very cool :D")
def pause(sec):
print(f"I waited for {sec} seconds!")
commands = {
"$help":help,
"$pause":pause,
"$say":say,
"$command1":command1,
"$command2":command2,
"$command3":command3,
}
with open("commands.json") as json_file:
help_json = json.load(json_file)
def call_command(BEFEHL):
function, *args = BEFEHL.split(' ')
commands[function](*args)
for line in user_input.split("\n"):
try:
call_command(line)
except KeyError:
print("This command does not exist.")
我用原始作者所做的列印陳述句替換了實際功能:D
這段代碼運行得很好,我開始著手對特定功能的描述。我創建了這個commands.json 例子:
{
"command1": ["This command is command 1. It prints out 'I am command 1' "],
"command2": ["This command is command 2. It prints out 'I am command 2' "],
"command3": ["This command is command 3. It prints out 'I am command 3' "]
}
有什么方法可以列印出命令后面的 json 中的內容嗎?一個示例用法是:
>>> $help command1
print("This is command 1. It prints out 'I am command 1' ")
我真的很感激知道這是否可能!:D
uj5u.com熱心網友回復:
當您加載 json 時,它基本上就像一個 Python 字典,因此您可以從它key作為引數傳遞的命令中檢索命令的描述。
您的help()函式應如下所示:
def help(*args):
if args == ():
for func_name, aliases in help_json.items():
print(func_name)
else:
print(help_json.get(args[0], "Command does not exist"))
第二個引數是在字典中找不到鍵"Command does not exist"時列印的默認值。get()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/475780.html
