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 '
Solution 1:
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() incommand: # 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.
forinputin raw_input.split():
ifinput.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!
.
Post a Comment for "Organizing A Large Python Script"