组织一个大的python脚本

Thu*_*nda 4 python python-2.7

我一直在研究一般的实用程序脚本,现在基本上只接受用户输入来执行某些任务,比如打开一个程序.在这个程序中,我将名称"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')
Run Code Online (Sandbox Code Playgroud)

ean*_*son 7

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

command = {}
command['skype'] = 'C:\Program Files (x86)\Skype\Phone', 'Skype.exe'
command['explorer'] = 'C:\Windows\', 'Explorer.exe'
Run Code Online (Sandbox Code Playgroud)

然后,您可以执行以下操作以根据用户输入执行正确的命令.

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)
Run Code Online (Sandbox Code Playgroud)

你可以找到更多的信息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)
Run Code Online (Sandbox Code Playgroud)

这将允许您发出类似的命令skype explorer,但请记住,没有拼写错误的空间,因此它们需要是完全匹配,除了空格之外什么也没有.作为一个例子,你可以写explorer,但不是explorer!.