4

我一直在研究一个通用实用程序脚本,它基本上只接受用户输入来执行一些任务,比如打开程序。在这个程序中,我将名称“command”定义为 raw_input,然后使用 if 语句检查命令列表(下面的小示例)。

不断使用 if 语句会使程序运行缓慢,所以我想知道是否有更好的方法,例如命令表?我对编程很陌生,所以不知道如何做到这一点。

import os
command = raw_input('What would you like to open:')

if 'skype' in command:
    os.chdir('C:\Program Files (x86)\Skype\Phone')
    os.startfile('Skype.exe')
4

1 回答 1

7

您可以将命令保存在带有元组的字典中,并执行类似的操作来存储命令。

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!

于 2012-12-24T23:03:00.677 回答