组织一个大型python脚本 [英] Organizing a large python script
问题描述
我一直在研究一个通用的实用程序脚本,现在它基本上只接受用户输入来执行一些任务,比如打开一个程序.在这个程序中,我将一个名称命令"定义为一个 raw_input,然后使用 if 语句来检查命令列表(下面的小例子).
I've been working on a general utility script for a while now that basically just accepts user input to preform some task like opening a program. In this program, I define a name "command" as a raw_input and then use if statements to check the list for a command (small example below).
不断使用 if 语句会使程序运行缓慢,所以我想知道是否有更好的方法,例如命令表?我对编程还很陌生,所以不确定如何实现这一点.
Constantly using if statements is making the program run slowly and so I'm wondering if there is a better way such as maybe a table of commands? I'm pretty new to programming so not sure how to accomplish this.
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')
推荐答案
您可以将命令保存在带有元组的字典中,并执行类似的操作来存储命令.
You can keep the commands in a dictionary with a tuple, and do something like this to store the commands.
command = {}
command['skype'] = 'C:\Program Files (x86)\Skype\Phone', 'Skype.exe'
command['explorer'] = 'C:\Windows\', 'Explorer.exe'
然后,您可以执行以下操作以根据用户输入执行正确的命令.
You could then do the following to execute the correct command based on the user input.
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
的更多信息 这里.
You can find more information on Dictionaries
and Tuples
here.
如果你需要允许多个命令,你可以用空格和将命令拆分成一个数组.
In case you need to allow multiple commands, you can separate them by a space and split the commands into an array.
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!
.
This would allow you to issue commands like skype explorer
, but keep in mind that there are no room for typos, so they need to be an exact match, separated with nothing but white-spaces. As an example you could write explorer
, but not explorer!
.
这篇关于组织一个大型python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!