1
Scripting Languages / How to create an in-program command shell [Python]
« on: August 21, 2015, 03:11:11 am »
You can create a dictionary in Python and use it to make a command shell style interface within your program. It's easier to work with and is more user friendly then a list of options with corresponding numbers. You can even add arguments or allow stacking a list of commands.
This works by creating a dictionary and a list of functions that contain the code that you want to execute when a command is run.
Next we create a dictionary with a string that is the command and corresponds to the function it should run.
Finally, we create a command prompt and then execute the function from the dictionary based on the command.
There's a few other things you can add that I didn't throw in for simplicity and because not everybody will want them. You can remove whitespace from the command or convert the command to lower case as a way of making commands case insensitive. You could add argument parsing by splitting the command string into a list and passing each argument into the function being run.
This works by creating a dictionary and a list of functions that contain the code that you want to execute when a command is run.
Next we create a dictionary with a string that is the command and corresponds to the function it should run.
Finally, we create a command prompt and then execute the function from the dictionary based on the command.
Code: [Select]
def welcome():
print 'Welcome to the demo program!'
def quit():
print 'Terminating...'
exit()
def begin():
print 'Please select an option below: (Demo only)'
commands = {
"welcome": welcome,
"quit": quit,
"begin": begin
}
while 1:
cmd = raw_input(" prompt> ")
commands[cmd]()
There's a few other things you can add that I didn't throw in for simplicity and because not everybody will want them. You can remove whitespace from the command or convert the command to lower case as a way of making commands case insensitive. You could add argument parsing by splitting the command string into a list and passing each argument into the function being run.
Code: [Select]
arguments = cmd.split(' ')
commands[cmd.lower()]()