In my last entry, I introduced Python as a quick and easy way to create GUI programs for Ubuntu. However, Python has a super-handy module for creating your own command-line interfaces, known simply as cmd. Specifically, cmd contains a minimal class representing a command-line shell, called Cmd. To create your own shells, you must subclass cmd.Cmd and add your own functionality there. Here's a minimal example of how to create a command-line shell wth Python:
#!/usr/bin/env python
import os,sys,cmd,shlex,readline
class Shell(cmd.Cmd):
def __init__(self,intro="Welcome to Shell):
cmd.Cmd.__init__(self,intro)
def do_prompt(self,line):
"Set the command prompt"
self.promptbackup="(Cmd) "
if line=="":
self.prompt=self.promptbackup
else:
self.prompt=line
do_man=do_help
def do_exit(self,line):
"Exit Shell"
return True
if __name__=="__main__":
Shell().cmdloop()
As you can see, it's a fairly trivial affair. Actual commands are
implemented as methods that begin with "do_". Exiting the shell
requires a method that returns True. You can even create scripts
for your shell, just like with any standard *nix shell or Windows
batch file.