python - 组织一个大型 python 脚本

标签 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')

最佳答案

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

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)

您可以找到有关字典元组 的更多信息here .

如果您需要允许多个命令,您可以用空格和split 分隔它们。将命令放入数组中。

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!

关于python - 组织一个大型 python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14026316/

相关文章:

python - 隐藏新 QApplication() 的 Python 启动器图标

python - 确保键的笛卡尔积出现在 Pandas 表中

algorithm - python中关键路径的变化

Mysql 在 python 中显示类型错误

python - 拆分列并写入单独的输出文件

python - 我陷入了 SKlearn 的属性错误

Python/Django - 为对象提供刚刚创建的外键时遇到问题

python - Pygame - 事件后 Sprite 的旋转不起作用

python - 是否可以从现有变量的名称中获取 PyObject 引用?

python - Pandas df.plot 子图上的多个传说?