[英] Load item description from json file
最近我看到一篇帖子,说有人制作了一个可以控制电脑的程序.(就是这个)Add commands to user input
在看了一些教程之后,我能够收发邮箱,并开始使用一些命令.首先,我添加了截图功能,这是最重要的功能.然后我添加了函数和命令来做其他事情.然后我想添加一个help命令,如果没有args,则显示所有命令,如果有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