Minor bump, but as op was originally talking about python I thought I throw maybe bit more pythonic example in about how to make in program shell. Most of you who have done some python coding are most likely familiar with cmd module which is part of standard library. Cmd module allows you quickly write own shell like application. It has automatic "help" command which usage is explained in my code example. It also has default tab autocompletion for made commands and previous commands can be displayed with up arrow.
Here is short example I quickly made to demostrate cmd modules usage. It mimics few familiar *nix commands in simple way.
#!/usr/bin/python
import cmd, os, sys
class terminal(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
self.prompt = "prompt> " #Default prompt is (Cmd)
#Word after "do_" is actual command
def do_echo(self,input_string, *args):
#*args is for some cmd module's default parameters
print input_string
def do_ls(self, *args):
"""List files in directory"""
#above comment makes actually help text which can be accessed via "help ls"
self.files = filter(os.path.isfile, os.listdir('.'))
self.dirs = filter(os.path.isdir, os.listdir('.'))
for f,d in zip(self.files, self.dirs):
print f,
print d,
print "/n"
def do_cat(self, file_,*args):
with open(file_, 'r') as self.f:
for self.line in self.f:
print self.line
def do_exit(self,*args):
sys.exit(0)
def do_EOF(self,*args):
#Exiting with ctrl+d. Throws error otherwise instead of exiting
sys.exit(0)
def cmdloop(self):
try:
cmd.Cmd.cmdloop(self)
except KeyboardInterrupt:
print "\n"
self.cmdloop()
except TypeError:
print "*** Invalid syntax"
self.cmdloop()
except IndexError:
print "*** Check arguments"
self.cmdloop()
if __name__=="__main__":
terminal().cmdloop()
Input after <command> is taken as one string, so for multiple arguments you can do same as suggested in op and use split(). But actual command string is automatically not part of the aguments.