Thunder Panda
Thunder Panda

Reputation: 73

Organizing a large python script

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).

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

Upvotes: 4

Views: 1662

Answers (1)

eandersson
eandersson

Reputation: 26352

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)

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)

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!.

Upvotes: 7

Related Questions