您可以将命令保存在带有元组的字典中,并执行类似的操作来存储命令。
command = {}
command['skype'] = 'C:\Program Files (x86)\Skype\Phone', 'Skype.exe'
command['explorer'] = 'C:\Windows\', 'Explorer.exe'
然后,您可以执行以下操作以根据用户输入执行正确的命令。
if raw_input.lower().strip() in command: # Check to see if input is defined in the dictionary.
os.chdir(command[raw_input][0]) # Gets Tuple item 0 (e.g. C:\Program Files.....)
os.startfile(command[myIraw_inputput][1]) # Gets Tuple item 1 (e.g. Skype.exe)
您可以在此处Dictionaries
找到更多信息。Tuples
如果您需要允许多个命令,您可以用空格分隔它们并将命令拆分为一个数组。
for input in raw_input.split():
if input.lower().strip() in command: # Check to see if input is defined in the dictionary.
os.chdir(command[input][0]) # Gets Tuple item 0 (e.g. C:\Program Files.....)
os.startfile(command[input][4]) # Gets Tuple item 1 (e.g. Skype.exe)
这将允许您发出类似的命令skype explorer
,但请记住,没有拼写错误的空间,因此它们需要完全匹配,仅用空格分隔。作为一个例子,你可以写explorer
,但不能explorer!
。