Organizing a large python script

I have been working on a common script utility for a long time, which basically just accepts user input for preliminary work on some task, for example, when opening a program. In this program, I define the name "command" as raw_input, and then use the if statements to check the list for the command (a small example below).

Constantly using if statements make the program run slowly, and so I wonder if there is a better way, for example, a command table? I am new to programming, so not sure how to do 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') 
+4
source share
1 answer

You can save the commands in a dictionary with a tuple and do something similar to store the commands.

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

You can then do the following to execute the correct command based on 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 (eg C:\Program Files.....) os.startfile(command[myIraw_inputput][1]) # Gets Tuple item 1 (eg Skype.exe) 

More information on Dictionaries and Tuples here .

If you need to allow multiple commands, you can split them into spaces and split 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 (eg C:\Program Files.....) os.startfile(command[input][4]) # Gets Tuple item 1 (eg Skype.exe) 

This will allow you to issue commands like skype explorer , but keep in mind that there is no room for typos, so they should be an exact match, separated only by white spaces. As an example, you can write explorer , but not explorer! .

+7
source

All Articles